id
int64
0
877k
file_name
stringlengths
3
109
file_path
stringlengths
13
185
content
stringlengths
31
9.38M
size
int64
31
9.38M
language
stringclasses
1 value
extension
stringclasses
11 values
total_lines
int64
1
340k
avg_line_length
float64
2.18
149k
max_line_length
int64
7
2.22M
alphanum_fraction
float64
0
1
repo_name
stringlengths
6
66
repo_stars
int64
94
47.3k
repo_forks
int64
0
12k
repo_open_issues
int64
0
3.4k
repo_license
stringclasses
11 values
repo_extraction_date
stringclasses
197 values
exact_duplicates_redpajama
bool
2 classes
near_duplicates_redpajama
bool
2 classes
exact_duplicates_githubcode
bool
2 classes
exact_duplicates_stackv2
bool
1 class
exact_duplicates_stackv1
bool
2 classes
near_duplicates_githubcode
bool
2 classes
near_duplicates_stackv1
bool
2 classes
near_duplicates_stackv2
bool
1 class
1,533,341
gameData.cpp
xavieran_BaKGL/bak/gameData.cpp
#include "bak/gameData.hpp" #include "bak/combat.hpp" #include "bak/save.hpp" #include "bak/spells.hpp" #include "bak/state/encounter.hpp" #include "bak/state/skill.hpp" #include "bak/container.hpp" #include "bak/inventory.hpp" #include "bak/timeExpiringState.hpp" #include "bak/types.hpp" #include "com/bits.hpp" #include "com/ostream.hpp" #include <variant> namespace BAK { GameData::GameData(const std::string& save) : mBuffer{FileBufferFactory::Get().CreateSaveBuffer(save)}, mLogger{Logging::LogState::GetLogger("GameData")}, mName{LoadSaveName(mBuffer)}, mChapter{LoadChapter()}, mMapLocation{LoadMapLocation()}, mLocation{LoadLocation()}, mTime{LoadWorldTime()}, mParty{LoadParty()} { mLogger.Info() << "Loading save: " << mBuffer.GetString() << std::endl; LoadChapterOffsetP(); //LoadCombatStats(0x914b, 1698); //LoadCombatClickedTimes(); } std::vector<TimeExpiringState> GameData::LoadTimeExpiringState() { // DialogAction value is always 4, flag is always 0x40 // ItemExpiring value is always 1, flag is always 0x80 // 0x80 adds mBuffer.Seek(sTimeExpiringEventRecordOffset); auto storage = std::vector<TimeExpiringState>{}; auto stateCount = mBuffer.GetUint16LE(); for (unsigned i = 0; i < stateCount; i++) { auto type = mBuffer.GetUint8(); auto flag = mBuffer.GetUint8(); auto data= mBuffer.GetUint16LE(); auto time = Time{mBuffer.GetUint32LE()}; storage.emplace_back(TimeExpiringState{ExpiringStateType{type}, flag, data, time}); mLogger.Info() << storage.back() << "\n"; } return storage; } SpellState GameData::LoadSpells() { mBuffer.Seek(sActiveSpells); return SpellState{mBuffer.GetUint16LE()}; } std::vector<SkillAffector> GameData::GetCharacterSkillAffectors( CharIndex character) { mBuffer.Seek(GetCharacterAffectorsOffset(character.mValue)); std::vector<SkillAffector> affectors{}; for (unsigned i = 0; i < 8; i++) { // Strength Drain Spell does this... // 00 01 08 00 07 00 D8 70 02 00 B0 E1 04 const auto type = mBuffer.GetUint16LE(); if (type == 0) { mBuffer.Skip(12); continue; } const auto skill = ToSkill(static_cast<BAK::SkillTypeMask>(mBuffer.GetUint16LE())); const auto adjust = mBuffer.GetSint16LE(); const auto startTime = Time{mBuffer.GetUint32LE()}; const auto endTime = Time{mBuffer.GetUint32LE()}; affectors.emplace_back(SkillAffector{type, skill, adjust, startTime, endTime}); } return affectors; } /* ************* LOAD Game STATE ***************** */ Party GameData::LoadParty() { auto characters = LoadCharacters(); auto activeCharacters = LoadActiveCharacters(); auto gold = LoadGold(); auto keys = LoadCharacterInventory(sPartyKeyInventoryOffset); auto party = Party{ gold, std::move(keys), characters, activeCharacters}; return party; } std::vector<Character> GameData::LoadCharacters() { unsigned characters = sCharacterCount; std::vector<Character> chars; for (unsigned character = 0; character < characters; character++) { mBuffer.Seek(GetCharacterNameOffset(character)); auto name = mBuffer.GetString(sCharacterNameLength); mBuffer.Seek(GetCharacterSkillOffset(character)); mLogger.Debug() << "Name: " << name << "@" << std::hex << mBuffer.Tell() << std::dec << "\n"; auto characterNameOffset = mBuffer.GetArray<2>(); auto spells = Spells{mBuffer.GetArray<6>()}; auto skills = LoadSkills(mBuffer); const auto pos = mBuffer.Tell(); for (unsigned i = 0; i < Skills::sSkills; i++) { const auto selected = State::ReadSkillSelected(mBuffer, character, i); const auto unseenImprovement = State::ReadSkillUnseenImprovement(mBuffer, character, i); skills.GetSkill(static_cast<SkillType>(i)).mSelected = selected; skills.GetSkill(static_cast<SkillType>(i)).mUnseenImprovement = unseenImprovement; } mBuffer.Seek(pos); skills.SetSelectedSkillPool(skills.CalculateSelectedSkillPool()); //bool characterIndex = mBuffer.GetUint8() != 0; auto unknown2 = mBuffer.GetArray<7>(); mLogger.Info() << " Finished loading : " << name << std::hex << mBuffer.Tell() << std::dec << "\n"; // Load inventory auto inventory = LoadCharacterInventory( GetCharacterInventoryOffset(character)); auto conditions = LoadConditions(character); chars.emplace_back( character, name, skills, spells, characterNameOffset, unknown2, conditions, std::move(inventory)); auto affectors = GetCharacterSkillAffectors(CharIndex{character}); for (const auto& affector : affectors) { chars.back().AddSkillAffector(affector); } } return chars; } Conditions GameData::LoadConditions(unsigned character) { ASSERT(character < sCharacterCount); mBuffer.Seek(GetCharacterConditionOffset(character)); auto conditions = Conditions{}; for (unsigned i = 0; i < Conditions::sNumConditions; i++) conditions.mConditions[i] = mBuffer.GetUint8(); return conditions; } unsigned GameData::LoadChapter() { mBuffer.Seek(sChapterOffset); auto chapter = mBuffer.GetUint16LE(); // next 4 uint16's might have something to do // with location displayed when chapter loaded mBuffer.Seek(0x64); auto chapterAgain = mBuffer.GetUint16LE(); assert(chapter == chapterAgain); return chapterAgain; } Royals GameData::LoadGold() { mBuffer.Seek(sGoldOffset); return Royals{mBuffer.GetUint32LE()}; } std::vector<CharIndex> GameData::LoadActiveCharacters() { mBuffer.Seek(sActiveCharactersOffset); const auto activeCharacters = mBuffer.GetUint8(); auto active = std::vector<CharIndex>{}; for (unsigned i = 0; i < activeCharacters; i++) { const auto c = mBuffer.GetUint8(); active.emplace_back(c); } mLogger.Debug() << "Active Characters: " << active << "\n"; return active; } MapLocation GameData::LoadMapLocation() { mBuffer.Seek(sMapPositionOffset); auto posX = mBuffer.GetUint16LE(); auto posY = mBuffer.GetUint16LE(); auto heading = mBuffer.GetUint16LE(); auto mapLocation = MapLocation{{posX, posY}, heading}; mLogger.Info() << mapLocation << "\n"; return mapLocation; } Location GameData::LoadLocation() { mBuffer.Seek(sLocationOffset); unsigned zone = mBuffer.GetUint8(); ASSERT(zone <= 12); mLogger.Info() << "LOADED: Zone:" << zone << std::endl; unsigned xtile = mBuffer.GetUint8(); unsigned ytile = mBuffer.GetUint8(); unsigned xpos = mBuffer.GetUint32LE(); unsigned ypos = mBuffer.GetUint32LE(); mLogger.Info() << "Unknown: " << mBuffer.GetArray<5>() << "\n"; std::uint16_t heading = mBuffer.GetUint16LE(); mLogger.Info() << "Tile: " << xtile << "," << ytile << std::endl; mLogger.Info() << "Pos: " << xpos << "," << ypos << std::endl; mLogger.Info() << "Heading: " << heading << std::endl; return Location{ ZoneNumber{zone}, {xtile, ytile}, GamePositionAndHeading{ GamePosition{xpos, ypos}, heading} }; } WorldClock GameData::LoadWorldTime() { mBuffer.Seek(sTimeOffset); return WorldClock{ Time{mBuffer.GetUint32LE()}, Time{mBuffer.GetUint32LE()}}; } Inventory GameData::LoadCharacterInventory(unsigned offset) { mBuffer.Seek(offset); const auto itemCount = mBuffer.GetUint8(); const auto capacity = mBuffer.GetUint16LE(); mLogger.Spam() << " Items: " << +itemCount << " cap: " << capacity << "\n"; return LoadInventory(mBuffer, itemCount, capacity); } std::vector<GenericContainer> GameData::LoadShops() { mBuffer.Seek(sShopsOffset); auto shops = std::vector<GenericContainer>{}; for (unsigned i = 0; i < sShopsCount; i++) { const unsigned address = mBuffer.Tell(); mLogger.Spam() << " Container: " << i << " addr: " << std::hex << address << std::dec << std::endl; auto container = LoadGenericContainer<ContainerGDSLocationTag>(mBuffer); shops.emplace_back(std::move(container)); mLogger.Spam() << shops.back() << "\n"; } return shops; } std::vector<GenericContainer> GameData::LoadContainers(unsigned zone) { const auto& mLogger = Logging::LogState::GetLogger("GameData"); mLogger.Spam() << "Loading containers for Z: " << zone << "\n"; std::vector<GenericContainer> containers{}; ASSERT(zone < sZoneContainerOffsets.size()); const auto [offset, count] = sZoneContainerOffsets[zone]; mBuffer.Seek(offset); for (unsigned j = 0; j < count; j++) { const unsigned address = mBuffer.Tell(); mLogger.Spam() << " Container: " << j << " addr: " << std::hex << address << std::dec << std::endl; auto container = LoadGenericContainer<ContainerWorldLocationTag>(mBuffer); containers.emplace_back(std::move(container)); mLogger.Spam() << containers.back() << "\n"; } return containers; } // add a memroy breakpoint on this? void GameData::LoadChapterOffsetP() { // I have no idea what these mean constexpr unsigned chapterOffsetsStart = 0x11a3; mBuffer.Seek(chapterOffsetsStart); mLogger.Debug() << "Chapter Offsets Start @" << std::hex << chapterOffsetsStart << std::dec << std::endl; for (unsigned i = 0; i < 10; i++) { std::stringstream ss{}; ss << "Chapter #" << i << " : " << mBuffer.GetUint16LE(); for (unsigned i = 0; i < 5; i++) { unsigned addr = mBuffer.GetUint32LE(); ss << " a: " << std::hex << addr << std::dec; } mLogger.Debug() << ss.str() << std::endl; } mLogger.Debug() << "Chapter Offsets End @" << std::hex << mBuffer.Tell() << std::dec << std::endl; } std::vector<CombatEntityList> GameData::LoadCombatEntityLists() { mBuffer.Seek(sCombatEntityListOffset); mLogger.Spam() << "Combat Entity Lists Start @" << std::hex << sCombatEntityListOffset << std::dec << std::endl; std::vector<CombatEntityList> data{}; for (int i = 0; i < sCombatEntityListCount; i++) { auto& list = data.emplace_back(); std::stringstream ss{}; ss << " Combat #" << i; constexpr unsigned maxCombatants = 7; auto sep = ' '; for (unsigned i = 0; i < maxCombatants; i++) { auto combatant = mBuffer.GetUint16LE(); if (combatant != 0xffff) { ss << sep << combatant; list.mCombatants.emplace_back(CombatantIndex{combatant}); } sep = ','; } mLogger.Spam() << ss.str() << std::endl; } mLogger.Spam() << "Combat Entity Lists End @" << std::hex << mBuffer.Tell() << std::dec << std::endl; return data; } void GameData::LoadCombatStats(unsigned offset, unsigned num) { unsigned combatStatsStart = offset; mBuffer.Seek(combatStatsStart); mLogger.Spam() << "Combat Stats Start @" << std::hex << combatStatsStart << std::dec << std::endl; // ends at 3070a for (unsigned i = 0; i < num; i++) { mLogger.Info() << "Combat #" << std::dec << i << " " << std::hex << mBuffer.Tell() << std::endl; mLogger.Spam() << std::hex << mBuffer.GetUint16LE() << std::endl << std::dec; auto spells = Spells(mBuffer.GetArray<6>()); auto skills = LoadSkills(mBuffer); mLogger.Info() << skills << "\n"; mBuffer.Skip(7); // Conditions? } mLogger.Spam() << "Combat Stats End @" << std::hex << mBuffer.Tell() << std::dec << std::endl; } std::vector<CombatGridLocation> GameData::LoadCombatGridLocations() { std::vector<CombatGridLocation> data{}; const auto initial = 0; mLogger.Spam() << "Loading Combat Grid Locations" << std::endl; mBuffer.Seek(sCombatGridLocationsOffset + (initial * 22)); for (unsigned i = 0; i < sCombatGridLocationsCount; i++) { mBuffer.Skip(2); const auto monsterType = mBuffer.GetUint16LE(); const auto gridX = mBuffer.GetUint8(); const auto gridY = mBuffer.GetUint8(); mBuffer.Skip(16); data.emplace_back(CombatGridLocation{MonsterIndex{monsterType}, glm::uvec2{gridX, gridY}}); } return data; } std::vector<CombatWorldLocation> GameData::LoadCombatWorldLocations() { std::vector<CombatWorldLocation> data{}; mBuffer.Seek(sCombatWorldLocationsOffset); for (unsigned k = 0; k < sCombatWorldLocationsCount; k++) { const auto x = mBuffer.GetUint32LE(); const auto y = mBuffer.GetUint32LE(); const auto heading = static_cast<std::uint16_t>(mBuffer.GetUint16LE() >> 8); const auto combatantPosition = GamePositionAndHeading{{x, y}, heading}; const auto unknownFlag = mBuffer.GetUint8(); const auto combatantState = mBuffer.GetUint8(); data.emplace_back(CombatWorldLocation{combatantPosition, unknownFlag, combatantState}); } return data; } std::vector<GenericContainer> GameData::LoadCombatInventories() { mLogger.Debug() << "Loading Combat Inventories" << std::endl; mBuffer.Seek(sCombatInventoryOffset); std::vector<GenericContainer> containers{}; // There are more combat inventories than there are // combatants for some reason. We should look them // up by combat and combatant number rather than by // index. for (unsigned i = 0; i < sCombatInventoryCount; i++) { auto loc = mBuffer.Tell(); auto container = LoadGenericContainer<ContainerCombatLocationTag>(mBuffer); containers.emplace_back(std::move(container)); mLogger.Debug() << "CobmatInventory #" << i << " @" << std::hex << loc << std::dec << " " << containers.back() << "\n"; } return containers; } void GameData::LoadCombatClickedTimes() { mLogger.Debug() << "Loading Combat Clicked Times" << std::endl; for (unsigned i = 0; i < 100; i++) { auto time = State::GetCombatClickedTime(mBuffer, i); if (time.mTime > 0) { mLogger.Debug() << "Combat #" << i << " time: " << time << "\n"; } } } }
14,618
C++
.cpp
394
30.961929
127
0.638857
xavieran/BaKGL
39
2
32
GPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,342
fixedObject.cpp
xavieran_BaKGL/bak/fixedObject.cpp
#include "bak/fixedObject.hpp" #include "bak/coordinates.hpp" #include "com/ostream.hpp" namespace BAK { std::vector<GenericContainer> LoadFixedObjects( unsigned targetZone) { std::vector<GenericContainer> fixedObjects; const auto& logger = Logging::LogState::GetLogger(__FUNCTION__); auto fb = FileBufferFactory::Get().CreateDataBuffer("OBJFIXED.DAT"); fb.DumpAndSkip(2); unsigned z = 1; while (fb.GetBytesLeft() > 0) { logger.Debug() << "Z: " << z++ << " @" << std::hex << fb.Tell() << std::dec << std::endl; auto objects = fb.GetUint16LE(); logger.Debug() << "Objects: " << objects << std::endl; for (unsigned i = 0; i < objects; i++) { auto container = LoadGenericContainer<ContainerWorldLocationTag>(fb); logger.Debug() << "Obj no: " << i << std::endl; logger.Debug() << container << std::endl; if (container.GetHeader().GetZone().mValue == targetZone) fixedObjects.emplace_back(std::move(container)); } } return fixedObjects; } }
1,100
C++
.cpp
29
31.275862
97
0.610954
xavieran/BaKGL
39
2
32
GPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,343
hotspotRef.cpp
xavieran_BaKGL/bak/hotspotRef.cpp
#include "bak/hotspotRef.hpp" #include <sstream> #include <iomanip> namespace BAK { std::string HotspotRef::ToString() const { std::stringstream ss{}; ss << std::dec << +mGdsNumber << mGdsChar; return ss.str(); } std::string HotspotRef::ToFilename() const { return "GDS" + ToString() + ".DAT"; } char MakeHotspotChar(std::uint8_t n) { // This is kinda weird... if (n == 0) return 'A'; return static_cast<char>(65 + n - 1); } std::ostream& operator<<(std::ostream& os, const HotspotRef& hr) { os << hr.ToString(); return os; } }
571
C++
.cpp
26
19.307692
64
0.650558
xavieran/BaKGL
39
2
32
GPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,344
bard.cpp
xavieran_BaKGL/bak/bard.cpp
#include "bak/bard.hpp" #include "bak/dialogSources.hpp" namespace BAK::Bard { BardStatus ClassifyBardAttempt(unsigned bardingSkill, unsigned innRequirement) { if (bardingSkill < innRequirement) { if (bardingSkill < ((innRequirement * 3) / 4)) { return BardStatus::Failed; } else { return BardStatus::Poor; } } else { if (bardingSkill < ((innRequirement + 100) / 2)) { return BardStatus::Good; } else { return BardStatus::Best; } } } Royals GetReward(BardStatus status, Sovereigns innReward, Chapter chapter) { const auto perChapterReward = (chapter.mValue - 1) * .05 * GetRoyals(innReward).mValue; const auto chapterReward = static_cast<unsigned>(std::round(perChapterReward)); const unsigned reward = GetRoyals(innReward).mValue + chapterReward; switch (status) { case BardStatus::Failed: return Royals{0}; case BardStatus::Poor: return Royals{reward / 4}; case BardStatus::Good: return Royals{reward / 2}; case BardStatus::Best: return Royals{reward}; default: ASSERT(false); return Royals{0}; } } void ReduceAvailableReward(ShopStats& stats, Royals reward) { if (reward.mValue > 0) { stats.mBardingReward = 0; // ????? this is referenced a bit strangely in the asm stats.mUnknown = 1; } } KeyTarget GetDialog(BardStatus status) { switch (status) { case BardStatus::Failed: return BAK::DialogSources::mBardingBad; case BardStatus::Poor: return BAK::DialogSources::mBardingPoor; case BardStatus::Good: return BAK::DialogSources::mBardingOkay; case BardStatus::Best: return BAK::DialogSources::mBardingGood; default: ASSERT(false); return KeyTarget{0}; } } SongIndex GetSong(BardStatus status) { switch (status) { case BardStatus::Failed: return SongIndex{0x3f0}; case BardStatus::Poor: return SongIndex{0x410}; case BardStatus::Good: return SongIndex{0x40f}; case BardStatus::Best: return SongIndex{0x3ef}; default: ASSERT(false); return SongIndex{0}; } } }
2,197
C++
.cpp
74
24.378378
91
0.664934
xavieran/BaKGL
39
2
32
GPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,345
dialogAction.cpp
xavieran_BaKGL/bak/dialogAction.cpp
#include "bak/dialogAction.hpp" #include "com/ostream.hpp" #include "graphics/glm.hpp" namespace BAK { std::ostream& operator<<(std::ostream& os, const DialogResult& d) { switch (d) { case DialogResult::SetTextVariable: return os << "SetTextVariable"; case DialogResult::GiveItem: return os << "GiveItem"; case DialogResult::LoseItem: return os << "LoseItem"; case DialogResult::SetFlag: return os << "SetFlag"; case DialogResult::LoadActor: return os << "LoadActor"; case DialogResult::SetPopupDimensions: return os << "SetPopupDimensions"; case DialogResult::SpecialAction: return os << "SpecialAction"; case DialogResult::GainCondition: return os << "GainCondition"; case DialogResult::GainSkill: return os << "GainSkill"; case DialogResult::LoadSkillValue: return os << "LoadSkillValue"; case DialogResult::PlaySound: return os << "PlaySound"; case DialogResult::ElapseTime: return os << "ElapseTime"; case DialogResult::SetAddResetState: return os << "SetAddResetState"; case DialogResult::FreeMemoryP: return os << "FreeMemoryP"; case DialogResult::PushNextDialog: return os << "PushNextDialog"; case DialogResult::UpdateCharacters: return os << "UpdateCharacters"; case DialogResult::HealCharacters: return os << "HealCharacters"; case DialogResult::LearnSpell: return os << "LearnSpell"; case DialogResult::Teleport: return os << "Teleport"; case DialogResult::SetEndOfDialogState: return os << "SetEndOfDialogState"; case DialogResult::SetTimeExpiringState: return os << "SetTimeExpiringState"; case DialogResult::LoseNOfItem: return os << "LoseNOfItem"; case DialogResult::BuggedAction: return os << "BuggedAction"; default: return os << "Unknown[" << static_cast<unsigned>(d) << "]"; } } std::ostream& operator<<(std::ostream& os, const SpecialActionType& a) { switch (a) { case SpecialActionType::ReduceGold: return os << "ReduceGold"; case SpecialActionType::IncreaseGold: return os << "IncreaseGold"; case SpecialActionType::RepairAllEquippedArmor: return os << "RepairAllEquippedArmor"; case SpecialActionType::ResetCombatState: return os << "ResetCombatState"; case SpecialActionType::SetCombatState: return os << "SetCombatState"; case SpecialActionType::CopyStandardInnToShop0: return os << "CopyStandardInnToShop0"; case SpecialActionType::CopyStandardInnToShop1: return os << "CopyStandardInnToShop1"; case SpecialActionType::Increase753f: return os << "Increase753f"; case SpecialActionType::Gamble: return os << "Gamble"; case SpecialActionType::RepairAndBlessEquippedSwords: return os << "RepairAndBlessEquippedSwords"; case SpecialActionType::ReturnAlcoholToShops: return os << "ReturnAlcoholToShops"; case SpecialActionType::ResetGambleValueTo: return os << "ResetGambleValueTo"; case SpecialActionType::BeginCombat: return os << "BeginCombat"; case SpecialActionType::ExtinguishAllLightSources: return os << "ExtinguishAllLightSources"; case SpecialActionType::EmptyArlieContainer: return os << "EmptyArlieContainer"; case SpecialActionType::CheatIncreaseSkill: return os << "CheatIncreaseSkill"; case SpecialActionType::UnifyOwynAndPugsSpells: return os << "UnifyOwynAndPugsSpells"; default: return os << "Unknown[" << static_cast<unsigned>(a) <<"]"; } } std::ostream& operator<<(std::ostream& os, const SetTextVariable& action) { os << "SetTextVariable { var: " << action.mWhich << ", set to: " << action.mWhat << " rest[" << std::hex << action.mRest << std::dec << "]}"; return os; } std::ostream& operator<<(std::ostream& os, const ElapseTime& action) { os << "ElapseTime { HowLong: " << action.mTime << " rest[" << std::hex << action.mRest << std::dec << "]}"; return os; } std::ostream& operator<<(std::ostream& os, const Teleport& action) { os << "Teleport{ Index: " << action.mIndex << " }"; return os; } std::ostream& operator<<(std::ostream& os, const UpdateCharacters& action) { os << "UpdateCharacters {" << action.mCharacters << "}"; return os; } std::ostream& operator<<(std::ostream& os, const LoseItem& action) { os << "LoseItem { what: " << action.mItemIndex << " amount: " << action.mQuantity << " rest[" << std::hex << action.mRest << std::dec << "]}"; return os; } std::ostream& operator<<(std::ostream& os, const GiveItem& action) { os << "GiveItem { what: " << +action.mItemIndex << " to: " << +action.mWho << " amount: " << +action.mQuantity << " rest[" << std::hex << action.mRest << std::dec << "]}"; return os; } std::ostream& operator<<(std::ostream& os, const SetFlag& action) { os << "SetFlag {" << std::hex << action.mEventPointer << " mask: " << +action.mEventMask << " data: " << +action.mEventData << " z: " << action.mAlwaysZero << " val: " << action.mEventValue << std::dec << "}"; return os; } std::ostream& operator<<(std::ostream& os, const LoadActor& action) { os << "LoadActor {Actors: (" << action.mActor1 << ", " << action.mActor2 << ", " << action.mActor3 << ") - " << action.mUnknown << ")}\n"; return os; } std::ostream& operator<<(std::ostream& os, const GainCondition& action) { os << "GainCondition{ who: " << action.mWho << " " << ToString(action.mCondition) << " [" << action.mMin << ", " << action.mMax << "]}"; return os; } std::ostream& operator<<(std::ostream& os, const GainSkill& action) { os << "GainSkill{ who: " << action.mWho << " " << ToString(action.mSkill) << " [" << +action.mMin << ", " << +action.mMax << "]}"; return os; } std::ostream& operator<<(std::ostream& os, const SpecialAction& action) { os << "SpecialAction{ Type: " << action.mType << " [" << action.mVar1 << ", " << action.mVar2 << ", " << action.mVar3 << "]}"; return os; } std::ostream& operator<<(std::ostream& os, const LoadSkillValue& action) { os << "LoadSkillValue{ target: " << action.mTarget << " " << ToString(action.mSkill) << "}"; return os; } std::ostream& operator<<(std::ostream& os, const PlaySound& action) { os << "PlaySound { index: " << action.mSoundIndex << " flag: " << action.mFlag << " " << action.mRest << "}"; return os; } std::ostream& operator<<(std::ostream& os, const SetPopupDimensions& action) { os << "SetPopupDimensions { pos: " << action.mPos << ", dims: " << action.mDims << "}"; return os; } std::ostream& operator<<(std::ostream& os, const PushNextDialog& action) { os << "PushNextDialog {" << action.mTarget << " rest[" << std::hex << action.mRest << std::dec << "]}"; return os; } std::ostream& operator<<(std::ostream& os, const SetAddResetState& action) { os << "SetAddResetState{" << std::hex << action.mEventPtr << " unk0: " << action.mUnknown0 << " TimeToExpire: " << std::dec << action.mTimeToExpire << "}"; return os; } std::ostream& operator<<(std::ostream& os, const SetTimeExpiringState& action) { os << "SetTimeExpiringState{" << std::hex << " type: " << action.mType << " flags: " << +action.mFlags << " eventPtr: " << action.mEventPtr << " TimeToExpire: " << std::dec << action.mTimeToExpire << "}"; return os; } std::ostream& operator<<(std::ostream& os, const HealCharacters& action) { os << "HealCharacters{who: " << action.mWho << " howMuch: " << action.mHowMuch << "}"; return os; } std::ostream& operator<<(std::ostream& os, const SetEndOfDialogState& action) { os << "SetEndOfDialogState{" << action.mState << " rest[" << std::hex << action.mRest << std::dec << "]}"; return os; } std::ostream& operator<<(std::ostream& os, const LearnSpell& action) { os << "LearnSpell{who: " << action.mWho << ", whichSpell: " << action.mWhichSpell << "}"; return os; } std::ostream& operator<<(std::ostream& os, const LoseNOfItem& action) { os << "LoseNOfItem { what: " << action.mItemIndex << " amount: " << action.mQuantity << " rest[" << std::hex << action.mRest << std::dec << "]}"; return os; } std::ostream& operator<<(std::ostream& os, const BuggedAction& action) { os << "BuggedAction { " << " rest[" << std::hex << action.mRest << std::dec << "]}"; return os; } std::ostream& operator<<(std::ostream& os, const UnknownAction& action) { os << "UnknownAction { " << " type: " << action.mType << " rest[" << std::hex << action.mRest << std::dec << "]}"; return os; } std::ostream& operator<<(std::ostream& os, const DialogAction& action) { std::visit([&os](const auto& a){ os << a; }, action); return os; } }
8,970
C++
.cpp
211
37.464455
106
0.631259
xavieran/BaKGL
39
2
32
GPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,346
worldFactory.cpp
xavieran_BaKGL/bak/worldFactory.cpp
#include "bak/worldFactory.hpp" #include "bak/imageStore.hpp" #include "bak/screen.hpp" #include "bak/textureFactory.hpp" #include "com/string.hpp" #include "bak/fileBufferFactory.hpp" namespace BAK { ZoneTextureStore::ZoneTextureStore( const ZoneLabel& zoneLabel, const BAK::Palette& palette) : mTextures{}, mTerrainOffset{0}, mHorizonOffset{0} { bool found = true; unsigned spriteSlot = 0; while (found) { auto spriteSlotLbl = zoneLabel.GetSpriteSlot(spriteSlot++); if ((found = FileBufferFactory::Get().DataBufferExists(spriteSlotLbl))) { auto fb = FileBufferFactory::Get().CreateDataBuffer(spriteSlotLbl); const auto sprites = LoadImages(fb); TextureFactory::AddToTextureStore( mTextures, sprites, palette); } } mTerrainOffset = GetTextures().size(); auto fb = FileBufferFactory::Get().CreateDataBuffer(zoneLabel.GetTerrain()); const auto terrain = LoadScreenResource(fb); TextureFactory::AddTerrainToTextureStore( mTextures, terrain, palette); mHorizonOffset = GetTextures().size(); const auto monsters = MonsterNames::Get(); for (unsigned i = 0; i < monsters.size(); i ++) { auto prefix = monsters.GetMonsterAnimationFile(MonsterIndex{i}); if (prefix == "") prefix = "ogr"; prefix = ToUpper(prefix); prefix += "1.BMX"; auto fb = FileBufferFactory::Get().CreateDataBuffer(prefix); const auto images = LoadImages(fb); auto pal = Palette{zoneLabel.GetPalette()}; const auto colorSwap = monsters.GetColorSwap(MonsterIndex{i}); if (colorSwap <= 9) { auto ss = std::stringstream{}; ss << "CS"; ss << +colorSwap << ".DAT"; const auto cs = ColorSwap{ss.str()}; pal = Palette{pal, cs}; } ASSERT(!images.empty()); TextureFactory::AddToTextureStore( mTextures, images[0], pal); } } std::ostream& operator<<(std::ostream& os, const ZoneItem& d) { os << d.mName << " :: "; //<< d.GetDatItem().mVertices << "\n"; for (const auto& face : d.GetFaces()) { for (const auto i : face) { os << " :: " << i; } os << "\n"; } return os; } Graphics::MeshObject ZoneItemToMeshObject( const ZoneItem& item, const ZoneTextureStore& store, const BAK::Palette& pal) { const auto& logger = Logging::LogState::GetLogger(__FUNCTION__); std::vector<glm::vec3> vertices; std::vector<glm::vec3> normals; std::vector<glm::vec4> colors; std::vector<glm::vec3> textureCoords; std::vector<float> textureBlends; std::vector<unsigned> indices; auto glmVertices = std::vector<glm::vec3>{}; const auto TextureBlend = [&](auto blend) { textureBlends.emplace_back(blend); textureBlends.emplace_back(blend); textureBlends.emplace_back(blend); }; for (const auto& vertex : item.GetVertices()) { glmVertices.emplace_back( glm::cast<float>(vertex) / BAK::gWorldScale); } unsigned index = 0; for (const auto& face : item.GetFaces()) { if (face.size() < 3) // line { auto start = glmVertices[face[0]]; auto end = glmVertices[face[1]]; auto normal = glm::normalize( glm::cross(end - start, glm::vec3(0, 0, 1.0))); float linewidth = 0.05f; indices.emplace_back(vertices.size()); vertices.emplace_back(start + linewidth * normal); indices.emplace_back(vertices.size()); vertices.emplace_back(end + linewidth * normal); indices.emplace_back(vertices.size()); vertices.emplace_back(start - linewidth * normal); indices.emplace_back(vertices.size()); vertices.emplace_back(end + linewidth * normal); indices.emplace_back(vertices.size()); vertices.emplace_back(start - linewidth * normal); indices.emplace_back(vertices.size()); vertices.emplace_back(end - linewidth * normal); normals.emplace_back(normal); normals.emplace_back(normal); normals.emplace_back(normal); normals.emplace_back(normal); normals.emplace_back(normal); normals.emplace_back(normal); auto colorIndex = item.GetColors().at(index); auto paletteIndex = item.GetPalettes().at(index); auto textureIndex = colorIndex; auto color = pal.GetColor(colorIndex); colors.emplace_back(color); colors.emplace_back(color); colors.emplace_back(color); colors.emplace_back(color); colors.emplace_back(color); colors.emplace_back(color); textureCoords.emplace_back(0.0, 0.0, textureIndex); textureCoords.emplace_back(0.0, 0.0, textureIndex); textureCoords.emplace_back(0.0, 0.0, textureIndex); textureCoords.emplace_back(0.0, 0.0, textureIndex); textureCoords.emplace_back(0.0, 0.0, textureIndex); textureCoords.emplace_back(0.0, 0.0, textureIndex); TextureBlend(0.0); TextureBlend(0.0); index++; continue; } unsigned triangles = face.size() - 2; // Whether to push this face away from the main plane // (needed to avoid z-fighting for some objects) bool push = item.GetPush().at(index); // Tesselate the face // Generate normals and new indices for each face vertex // The normal must be inverted to account // for the Y direction being negated auto normal = glm::normalize( glm::cross( glmVertices[face[0]] - glmVertices[face[2]], glmVertices[face[0]] - glmVertices[face[1]])); if (item.IsSprite()) { normal = glm::cross(normal, glm::vec3{1, 0, 1}); } for (unsigned triangle = 0; triangle < triangles; triangle++) { auto i_a = face[0]; auto i_b = face[triangle + 1]; auto i_c = face[triangle + 2]; normals.emplace_back(normal); normals.emplace_back(normal); normals.emplace_back(normal); glm::vec3 zOff = normal; if (push) zOff = glm::vec3{0}; vertices.emplace_back(glmVertices[i_a] - zOff * 0.02f); indices.emplace_back(vertices.size() - 1); vertices.emplace_back(glmVertices[i_b] - zOff * 0.02f); indices.emplace_back(vertices.size() - 1); vertices.emplace_back(glmVertices[i_c] - zOff * 0.02f); indices.emplace_back(vertices.size() - 1); // Hacky - only works for quads - but the game only // textures quads anyway... (not true...) auto colorIndex = item.GetColors().at(index); auto paletteIndex = item.GetPalettes().at(index); auto textureIndex = colorIndex; float u = 1.0; float v = 1.0; auto maxDim = store.GetMaxDim(); // I feel like these "palettes" are probably collections of // flags? static constexpr std::uint8_t texturePalette0 = 0x90; static constexpr std::uint8_t texturePalette1 = 0x91; static constexpr std::uint8_t texturePalette2 = 0xd1; // texturePalette3 is optional and puts grass on mountains static constexpr std::uint8_t texturePalette3 = 0x81; static constexpr std::uint8_t texturePalette4 = 0x11; static constexpr std::uint8_t terrainPalette = 0xc1; // terrain palette // 0 = ground // 1 = road // 2 = waterfall // 3 = path // 4 = dirt/field // 5 = river // 6 = sand // 7 = riverbank if (item.GetName().substr(0, 2) == "t0") { if (textureIndex == 1) { textureIndex = store.GetTerrainOffset(BAK::Terrain::Road); TextureBlend(1.0); } else if (textureIndex == 2) { textureIndex = store.GetTerrainOffset(BAK::Terrain::Path); TextureBlend(1.0); } else if (textureIndex == 3) { textureIndex = store.GetTerrainOffset(BAK::Terrain::River); TextureBlend(1.0); } else { TextureBlend(0.0); } } else if (item.GetName().substr(0, 2) == "r0") { if (textureIndex == 3) { textureIndex = store.GetTerrainOffset(BAK::Terrain::River); TextureBlend(1.0); } else if (textureIndex == 5) { textureIndex = store.GetTerrainOffset(BAK::Terrain::Bank); TextureBlend(1.0); } else { TextureBlend(0.0); } } else if (item.GetName().substr(0, 2) == "g0") { if (textureIndex == 0) { textureIndex = store.GetTerrainOffset(BAK::Terrain::Ground); TextureBlend(1.0); } else if (textureIndex == 5) { textureIndex = store.GetTerrainOffset(BAK::Terrain::River); TextureBlend(1.0); } else { TextureBlend(0.0); } } else if (item.GetName().substr(0, 5) == "field") { if (textureIndex == 1) { textureIndex = store.GetTerrainOffset(BAK::Terrain::Dirt); TextureBlend(1.0); } else if (textureIndex == 2) { textureIndex = store.GetTerrainOffset(BAK::Terrain::Bank); TextureBlend(1.0); } else { TextureBlend(1.0); } } else if (item.GetName().substr(0, 4) == "fall" || item.GetName().substr(0, 6) == "spring") { if (textureIndex == 3) { textureIndex = store.GetTerrainOffset(BAK::Terrain::River); TextureBlend(1.0); } else if (textureIndex == 5) { textureIndex = store.GetTerrainOffset(BAK::Terrain::Bank); TextureBlend(1.0); } else if (textureIndex == 6) { textureIndex = store.GetTerrainOffset(BAK::Terrain::Waterfall); TextureBlend(1.0); } else { TextureBlend(0.0); } } else if (paletteIndex == terrainPalette) { textureIndex += store.GetTerrainOffset(BAK::Terrain::Ground); TextureBlend(1.0); } else if (paletteIndex == texturePalette0 || paletteIndex == texturePalette1 || paletteIndex == texturePalette2 || paletteIndex == texturePalette4) { TextureBlend(1.0); } else { TextureBlend(0.0); } if (colorIndex < store.GetTextures().size()) { u = static_cast<float>(store.GetTexture(textureIndex).GetWidth() - 1) / static_cast<float>(maxDim); v = static_cast<float>(store.GetTexture(textureIndex).GetHeight() - 1) / static_cast<float>(maxDim); } // controls the size of the "pixel" effect of the ground if (item.GetName().substr(0, 6) == "ground") { u *= 40; v *= 40; } if (triangle == 0) { textureCoords.emplace_back(u , v, textureIndex); textureCoords.emplace_back(0.0, v, textureIndex); textureCoords.emplace_back(0.0, 0.0, textureIndex); } else { textureCoords.emplace_back(u, v, textureIndex); textureCoords.emplace_back(0.0, 0.0, textureIndex); textureCoords.emplace_back(u, 0.0, textureIndex); } auto color = pal.GetColor(colorIndex); // bitta fun if (item.GetName().substr(0, 5) == "cryst") color.a = 0.8; colors.emplace_back(color); colors.emplace_back(color); colors.emplace_back(color); } index++; } assert(vertices.size() == normals.size()); assert(vertices.size() == colors.size()); assert(vertices.size() == textureCoords.size()); assert(vertices.size() == textureBlends.size()); assert(vertices.size() == indices.size()); return Graphics::MeshObject{ vertices, normals, colors, textureCoords, textureBlends, indices}; } std::ostream& operator<<(std::ostream& os, const WorldItemInstance& d) { os << "[ Name: " << d.GetZoneItem().GetName() << " Type: " << d.mType << " Rot: " << glm::to_string(d.mRotation) << " Loc: " << glm::to_string(d.mLocation) << "]"; os << std::endl << " Vertices::" << std::endl; const auto& vertices = d.GetZoneItem().GetVertices(); for (const auto& vertex : vertices) { os << " " << glm::to_string(vertex) << std::endl; } return os; } }
14,358
C++
.cpp
382
25.371728
87
0.517617
xavieran/BaKGL
39
2
32
GPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,347
spells.cpp
xavieran_BaKGL/bak/spells.cpp
#include "bak/spells.hpp" #include "bak/objectInfo.hpp" #include <iostream> namespace BAK { std::ostream& operator<<(std::ostream& os, StaticSpells s) { using enum StaticSpells; switch (s) { case DragonsBreath: return os << "Dragons Breath"; case CandleGlow: return os << "Candle Glow"; case Stardusk: return os << "Stardusk"; case AndTheLightShallLie: return os << " And The Light Shall Lie"; case Union: return os << "Union"; case ScentOfSarig: return os << "Scent Of Sarig"; default: return os << "Unknown Static Spell [" << static_cast<unsigned>(s) << "]"; } } StaticSpells ToStaticSpell(SpellIndex s) { switch (s.mValue) { case 0: return StaticSpells::DragonsBreath; case 2: return StaticSpells::CandleGlow; case 26: return StaticSpells::Stardusk; case 34: return StaticSpells::Union; case 35: return StaticSpells::AndTheLightShallLie; case 8: return StaticSpells::ScentOfSarig; default: return static_cast<StaticSpells>(-1); } } std::string_view ToString(SpellCalculationType s) { using enum SpellCalculationType; switch (s) { case NonCostRelated: return "NonCostRelated"; case FixedAmount: return "FixedAmount"; case CostTimesDamage: return "CostTimesDamage"; case CostTimesDuration: return "CostTimesDuration"; case Special1: return "Special1"; case Special2: return "Special2"; default: return "Unknown"; } } std::ostream& operator<<(std::ostream& os, SpellCalculationType s) { return os << ToString(s); } std::ostream& operator<<(std::ostream& os, const Spells& s) { return os << "Spells{" << std::hex << s.GetSpells() << std::dec << "}"; } std::ostream& operator<<(std::ostream& os, const Spell& s) { return os << "Spell{" << s.mIndex << " - " << s.mName << " minCost: " << s.mMinCost << " maxCost: " << s.mMaxCost << " isCmbt: " << s.mIsMartial << " targTp: " << s.mTargetingType << " effCol: " << s.mColor << " anim: " << s.mAnimationEffectType << " objReq: " << s.mObjectRequired << " (" << (s.mObjectRequired ? *s.mObjectRequired : ItemIndex{0}) << ")" << " calcTp: " << s.mCalculationType << " dmg: " << s.mDamage << " len: " << s.mDuration << "}"; } }
2,335
C++
.cpp
65
30.846154
88
0.631416
xavieran/BaKGL
39
2
32
GPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,348
imageStore.cpp
xavieran_BaKGL/bak/imageStore.cpp
#include "bak/imageStore.hpp" #include "bak/dataTags.hpp" #include "com/logger.hpp" #include <iostream> namespace BAK { std::vector<Image> LoadImagesNormal(FileBuffer& fb) { std::vector<Image> images{}; const unsigned compression = fb.GetUint16LE(); const unsigned numImages = fb.GetUint16LE(); std::vector<unsigned> imageSizes{}; fb.Skip(2); unsigned int size = fb.GetUint32LE(); for (unsigned i = 0; i < numImages; i++) { imageSizes.emplace_back(fb.GetUint16LE()); unsigned flags = fb.GetUint16LE(); unsigned width = fb.GetUint16LE(); unsigned height = fb.GetUint16LE(); images.emplace_back(width, height, flags, false); } if (compression == 1) { // Not sure why this is needed or if *2 is the right number size *= 2; } FileBuffer decompressed = FileBuffer(size); fb.Decompress(&decompressed, compression); for (unsigned int i = 0; i < numImages; i++) { auto imageBuffer = FileBuffer(imageSizes[i]); imageBuffer.Fill(&decompressed); images[i].Load(&imageBuffer); } return images; } std::vector<Image> LoadImagesTagged(FileBuffer& fb) { auto infBuf = fb.Find(DataTag::INF); std::vector<Image> images{}; unsigned imageCount = infBuf.GetUint16LE(); for (unsigned i = 0; i < imageCount; i++) { const auto width = infBuf.GetUint16LE(); const auto start = infBuf.Tell(); infBuf.Skip(2 * (imageCount - 1)); const auto height = infBuf.GetUint16LE(); infBuf.Seek(start); images.emplace_back(width, height, 0, true); } auto binBuf = fb.Find(DataTag::BIN); auto compression = binBuf.GetUint8(); auto size = binBuf.GetUint32LE(); FileBuffer decompressed = FileBuffer(size); auto decompressedBytes = binBuf.DecompressLZW(&decompressed); for (unsigned i = 0; i < imageCount; i++) { images[i].Load(&decompressed); } return images; } std::vector<Image> LoadImages(FileBuffer& fb) { const auto imageType = fb.GetUint16LE(); if (imageType == 0x1066) { return LoadImagesNormal(fb); } else if (imageType == 0x4d42) { return LoadImagesTagged(fb); } else { throw std::runtime_error("Couldn't load images"); return std::vector<Image>{}; } } }
2,377
C++
.cpp
79
24.594937
67
0.6417
xavieran/BaKGL
39
2
32
GPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,349
combat.cpp
xavieran_BaKGL/bak/combat.cpp
#include "bak/combat.hpp" #include "bak/fileBufferFactory.hpp" #include "com/ostream.hpp" #include "com/logger.hpp" #include <sstream> namespace BAK { std::ostream& operator<<(std::ostream& os, const CombatWorldLocation& cwl) { os << "CombatWorldLocation{" << cwl.mPosition << " Unk: " << +cwl.mUnknownFlag << " State: " << +cwl.mState << "}"; return os; } std::ostream& operator<<(std::ostream& os, const CombatGridLocation& cgl) { os << "CombatGridLocation{ Monster: " << cgl.mMonster << " pos: " << cgl.mGridPos << "}"; return os; } std::ostream& operator<<(std::ostream& os, const CombatEntityList& cel) { os << "CombatEntityList{" << cel.mCombatants << "}"; return os; } void LoadP1Dat() { auto fb = FileBufferFactory::Get().CreateDataBuffer("P1.DAT"); std::stringstream ss{}; for (unsigned j = 0; j < 7; j++) { for (unsigned i = 0; i < 16; i++) { ss << " " << +fb.GetUint8(); } Logging::LogDebug(__FUNCTION__) << "Skills? " << ss.str() << "\n"; ss = {}; } Logging::LogDebug(__FUNCTION__) << "Remaining: " << fb.GetBytesLeft() << "\n"; } }
1,164
C++
.cpp
38
26.5
93
0.591928
xavieran/BaKGL
39
2
32
GPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,350
entityType.cpp
xavieran_BaKGL/bak/entityType.cpp
#include "bak/entityType.hpp" namespace BAK { unsigned GetContainerTypeFromEntityType(EntityType et) { using enum EntityType; switch (et) { case BAG: return 0; case CHEST: return 1; case DIRTPILE: return 2; case TOMBSTONE: return 3; case DEADBODY1: [[fallthrough]]; case DEADBODY2: return 4; case TRAP: return 5; case BUSH1: [[fallthrough]]; case BUSH2: [[fallthrough]]; case BUSH3: return 6; // 7 is shop, which is not an entity case CRYST: return 8; case STUMP: return 9; case BUILDING: return 10; default: return 0; } } EntityType EntityTypeFromModelName(std::string_view name) { if (name.substr(0, 3) == "box") return EntityType::CHEST; if (name.substr(0, 5) == "chest") return EntityType::CHEST; if (name.substr(0, 4) == "gate") return EntityType::GATE; if (name.substr(0, 5) == "stump") return EntityType::STUMP; return EntityType::CHEST; } }
1,008
C++
.cpp
33
24.727273
63
0.631687
xavieran/BaKGL
39
2
32
GPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,351
save.cpp
xavieran_BaKGL/bak/save.cpp
#include "bak/save.hpp" #include "bak/gameData.hpp" namespace BAK { void Save(const Inventory& inv, FileBuffer& fb) { const auto itemCount = inv.GetNumberItems(); const auto capacity = inv.GetCapacity(); unsigned i = 0; for (; i < itemCount; i++) { const auto& item = inv.GetAtIndex(InventoryIndex{i}); fb.PutUint8(item.GetItemIndex().mValue); fb.PutUint8(item.GetCondition()); fb.PutUint8(item.GetStatus()); fb.PutUint8(item.GetModifierMask()); } for (; i < capacity; i++) fb.Skip(4); } void Save(const GenericContainer& gc, FileBuffer& fb) { // Write container header fb.Seek(gc.GetHeader().GetAddress()); fb.Skip(12); // Skip mLocation, that won't change fb.Skip(1); // Skip mLocationType fb.PutUint8(gc.GetInventory().GetNumberItems()); fb.Skip(1); fb.Skip(1); Save(gc.GetInventory(), fb); if (gc.HasLock()) { const auto& lock = gc.GetLock(); fb.PutUint8(lock.mLockFlag); fb.PutUint8(lock.mRating); fb.PutUint8(lock.mFairyChestIndex); fb.PutUint8(lock.mTrapDamage); } if (gc.HasDoor()) { fb.Skip(2); // No need to write anything for doors } if (gc.HasDialog()) fb.Skip(6); // Don't need to write anything for dialog if (gc.HasShop()) { const auto& shop = gc.GetShop(); fb.PutUint8(shop.mTempleNumber); fb.PutUint8(shop.mSellFactor); fb.PutUint8(shop.mMaxDiscount); fb.PutUint8(shop.mBuyFactor); fb.PutUint8(shop.mHaggleDifficulty); fb.PutUint8(shop.mHaggleAnnoyanceFactor); fb.PutUint8(shop.mBardingSkill); fb.PutUint8(shop.mBardingReward); fb.PutUint8(shop.mBardingMaxReward); fb.PutUint8(shop.mUnknown); fb.PutUint8(shop.mInnSleepTilHour); fb.PutUint8(shop.mInnCost); fb.PutUint8(shop.mRepairTypes); fb.PutUint8(shop.mRepairFactor); fb.PutUint16LE(shop.mCategories); } if (gc.HasEncounter()) fb.Skip(9); // Don't need to write anything for encounter if (gc.HasLastAccessed()) fb.PutUint32LE(gc.GetLastAccessed().mTime); } void Save(const Character& c, FileBuffer& fb) { const auto charIndex = c.mCharacterIndex.mValue; // Skills fb.Seek(BAK::GameData::GetCharacterSkillOffset(charIndex)); fb.Skip(2); // Character name offset auto* spells = reinterpret_cast<const std::uint8_t*>(&c.GetSpells().GetSpellBytes()); for (unsigned i = 0; i < 6; i++) { fb.PutUint8(spells[i]); } const auto& skills = c.GetSkills(); for (unsigned i = 0; i < Skills::sSkills; i++) { const auto& skill = skills.GetSkill(static_cast<BAK::SkillType>(i)); fb.PutUint8(skill.mMax); fb.PutUint8(skill.mTrueSkill); fb.PutUint8(skill.mCurrent); fb.PutUint8(skill.mExperience); fb.PutUint8(skill.mModifier); const auto pos = fb.Tell(); // FIXME: set skill selected, set skill unseen improvement... } // Inventory fb.Seek(BAK::GameData::GetCharacterInventoryOffset(charIndex)); fb.PutUint8(c.GetInventory().GetNumberItems()); fb.PutUint16LE(c.GetInventory().GetCapacity()); Save(c.GetInventory(), fb); // Conditions fb.Seek(BAK::GameData::GetCharacterConditionOffset(charIndex)); for (unsigned i = 0; i < Conditions::sNumConditions; i++) { const auto cond = c.mConditions.GetCondition(static_cast<BAK::Condition>(i)); fb.PutUint8(cond.Get()); } fb.Seek(BAK::GameData::GetCharacterAffectorsOffset(charIndex)); for (const auto& affector : c.GetSkillAffectors()) { fb.PutUint16LE(affector.mType); fb.PutUint16LE(1 << static_cast<std::uint16_t>(affector.mSkill)); fb.PutSint16LE(affector.mAdjustment); fb.PutUint32LE(affector.mStartTime.mTime); fb.PutUint32LE(affector.mEndTime.mTime); } } void Save(const Party& party, FileBuffer& fb) { fb.Seek(GameData::sGoldOffset); fb.PutUint32LE(party.GetGold().mValue); for (const auto& character : party.mCharacters) { Save(character, fb); } fb.Seek(BAK::GameData::sPartyKeyInventoryOffset); fb.PutUint8(party.GetKeys().GetInventory().GetNumberItems()); fb.PutUint16LE(party.GetKeys().GetInventory().GetCapacity()); Save(party.GetKeys().GetInventory(), fb); fb.Seek(GameData::sActiveCharactersOffset); fb.PutUint8(party.mActiveCharacters.size()); for (const auto charIndex : party.mActiveCharacters) fb.PutUint8(charIndex.mValue); } void Save(const WorldClock& worldClock, FileBuffer& fb) { fb.Seek(GameData::sTimeOffset); fb.PutUint32LE(worldClock.GetTime().mTime); fb.PutUint32LE(worldClock.GetTimeLastSlept().mTime); } void Save(const std::vector<TimeExpiringState>& storage, FileBuffer& fb) { fb.Seek(GameData::sTimeExpiringEventRecordOffset); fb.PutUint16LE(storage.size()); for (const auto& state : storage) { fb.PutUint8(static_cast<std::uint8_t>(state.mType)); fb.PutUint8(state.mFlags); fb.PutUint16LE(state.mData); fb.PutUint32LE(state.mDuration.mTime); } } void Save(const SpellState& spells, FileBuffer& fb) { fb.Seek(GameData::sActiveSpells); fb.PutUint16LE(spells.GetSpells()); } void Save(Chapter chapter, FileBuffer& fb) { fb.Seek(GameData::sChapterOffset); fb.PutUint16LE(chapter.mValue); // Chapter again..? fb.Seek(0x64); fb.PutUint16LE(chapter.mValue); } void Save(const MapLocation& location, FileBuffer& fb) { fb.Seek(GameData::sMapPositionOffset); fb.PutUint16LE(location.mPosition.x); fb.PutUint16LE(location.mPosition.y); fb.PutUint16LE(location.mHeading); } void Save(const Location& location, FileBuffer& fb) { fb.Seek(GameData::sLocationOffset); fb.PutUint8(location.mZone.mValue); fb.PutUint8(location.mTile.x); fb.PutUint8(location.mTile.y); fb.PutUint32LE(location.mLocation.mPosition.x); fb.PutUint32LE(location.mLocation.mPosition.y); fb.Skip(5); fb.PutUint16LE(location.mLocation.mHeading); } }
6,160
C++
.cpp
179
28.821229
89
0.676861
xavieran/BaKGL
39
2
32
GPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,352
dialogReplacements.cpp
xavieran_BaKGL/bak/dialogReplacements.cpp
#include "bak/dialogReplacements.hpp" namespace BAK { void Replacements::ReplaceActions(OffsetTarget target, std::vector<DialogAction>& actions) { for (const auto& replacement : sReplacements) { if (replacement.mTarget == target) { for (const auto& action : replacement.mReplacements) { assert(actions.size() > action.first); actions[action.first] = action.second; } } } } const std::vector<Replacement> Replacements::sReplacements = { Replacement{OffsetTarget{31, 0xb0f}, { {0, PlaySound{34, 0, {}}} }}, Replacement{OffsetTarget{31, 0xe35}, { {0, PlaySound{72, 0, {}}}, {1, PlaySound{72, 0, {}}}, {2, PlaySound{72, 0, {}}} }}, Replacement{OffsetTarget{31, 0xf5a}, { {0, PlaySound{34, 0, {}}}, {1, PlaySound{38, 0, {}}}, {2, PlaySound{60, 2, {}}}, {3, PlaySound{40, 2, {}}}, {4, PlaySound{53, 2, {}}} }}, Replacement{OffsetTarget{31, 0x1196}, { {0, PlaySound{34, 0, {}}}, {1, PlaySound{34, 1, {}}}, }}, Replacement{OffsetTarget{31, 0x11f3}, { {0, PlaySound{34, 0, {}}}, }}, Replacement{OffsetTarget{31, 0x139c}, { {0, PlaySound{5, 0, {}}}, }}, Replacement{OffsetTarget{31, 0x1cfc}, { {0, PlaySound{34, 0, {}}}, {1, PlaySound{34, 0, {}}}, }}, Replacement{OffsetTarget{31, 0x1db8}, { {0, PlaySound{39, 2, {}}}, }}, Replacement{OffsetTarget{31, 0x21da}, { {0, PlaySound{38, 0, {}}}, }}, Replacement{OffsetTarget{31, 0x30ff}, { {0, PlaySound{34, 0, {}}}, {1, PlaySound{34, 0, {}}}, }}, Replacement{OffsetTarget{31, 0x336d}, { {0, PlaySound{38, 0, {}}}, }}, Replacement{OffsetTarget{31, 0x34bf}, { {0, PlaySound{34, 0, {}}}, }}, Replacement{OffsetTarget{31, 0x3564}, { {0, PlaySound{34, 1, {}}}, }}, Replacement{OffsetTarget{31, 0x3816}, { {0, PlaySound{34, 0, {}}}, }}, Replacement{OffsetTarget{31, 0x3a12}, { {0, PlaySound{38, 2, {}}}, }}, Replacement{OffsetTarget{31, 0x4054}, { {0, PlaySound{34, 0, {}}}, }}, Replacement{OffsetTarget{31, 0x445f}, { {0, PlaySound{38, 1, {}}}, }}, Replacement{OffsetTarget{31, 0x4830}, { {0, PlaySound{34, 0, {}}}, }}, Replacement{OffsetTarget{31, 0x5170}, { {0, PlaySound{34, 0, {}}}, }}, Replacement{OffsetTarget{31, 0x52a8}, { {0, PlaySound{34, 0, {}}}, {1, PlaySound{34, 0, {}}}, {2, PlaySound{34, 1, {}}}, }}, Replacement{OffsetTarget{31, 0x5479}, { {0, PlaySound{75, 1, {}}}, }}, Replacement{OffsetTarget{31, 0x5503}, { {0, PlaySound{67, 0, {}}}, {1, PlaySound{67, 0, {}}}, {2, PlaySound{67, 0, {}}}, }}, Replacement{OffsetTarget{31, 0x57db}, { {0, PlaySound{38, 0, {}}}, }}, Replacement{OffsetTarget{31, 0x61ae}, { {0, PlaySound{38, 0, {}}}, }}, Replacement{OffsetTarget{31, 0x66d5}, { {0, PlaySound{72, 0, {}}}, {1, PlaySound{72, 0, {}}}, {2, PlaySound{72, 0, {}}}, }}, Replacement{OffsetTarget{31, 0x694e}, { {0, PlaySound{38, 2, {}}}, }}, Replacement{OffsetTarget{31, 0x6e2e}, { {0, PlaySound{67, 0, {}}}, {1, PlaySound{67, 0, {}}}, {2, PlaySound{67, 0, {}}}, }}, Replacement{OffsetTarget{31, 0x6f08}, { {0, PlaySound{34, 0, {}}}, {1, PlaySound{38, 2, {}}}, }}, Replacement{OffsetTarget{31, 0x7293}, { {0, PlaySound{38, 1, {}}}, {1, PlaySound{39, 2, {}}}, }}, Replacement{OffsetTarget{31, 0x75a2}, { {0, PlaySound{39, 1, {}}}, {1, PlaySound{66, 1, {}}}, }}, Replacement{OffsetTarget{31, 0x77fe}, { {0, PlaySound{38, 0, {}}}, }}, Replacement{OffsetTarget{31, 0x7fc1}, { {0, PlaySound{34, 0, {}}}, {1, PlaySound{34, 1, {}}}, }}, Replacement{OffsetTarget{31, 0x892f}, { {0, PlaySound{38, 0, {}}}, }}, Replacement{OffsetTarget{31, 0x8ca8}, { {0, PlaySound{38, 2, {}}}, {1, PlaySound{34, 0, {}}}, }}, Replacement{OffsetTarget{31, 0x8eb8}, { {0, PlaySound{67, 0, {}}}, {1, PlaySound{67, 0, {}}}, {2, PlaySound{67, 0, {}}}, }}, Replacement{OffsetTarget{31, 0x91b5}, { {0, PlaySound{34, 0, {}}}, }}, Replacement{OffsetTarget{31, 0x95dc}, { {0, PlaySound{67, 0, {}}}, {1, PlaySound{38, 1, {}}}, {2, PlaySound{40, 1, {}}}, }}, Replacement{OffsetTarget{31, 0x9d2f}, { {0, SetTextVariable{0, 13, {}}}, {1, GainSkill{2, SkillType::TotalHealth, -4120, -2560}}, {2, PlaySound{26, 1, {}}}, {3, PlaySound{40, 1, {}}}, }}, Replacement{OffsetTarget{31, 0xa134}, { {0, LoseItem{53, 25, {}}}, {1, PlaySound{64, 0, {}}}, {2, PlaySound{64, 0, {}}}, {3, PlaySound{63, 1, {}}}, }}, Replacement{OffsetTarget{31, 0xab5c}, { {0, PlaySound{34, 0, {}}}, {1, PlaySound{34, 0, {}}}, }}, Replacement{OffsetTarget{31, 0xb7af}, { {0, PlaySound{34, 0, {}}}, }}, Replacement{OffsetTarget{31, 0xc35e}, { {0, PlaySound{34, 0, {}}}, {1, PlaySound{39, 2, {}}}, }}, Replacement{OffsetTarget{31, 0xc5e9}, { {0, PlaySound{34, 0, {}}}, {1, PlaySound{34, 1, {}}}, }}, Replacement{OffsetTarget{31, 0xc6b8}, { {0, PlaySound{34, 0, {}}}, }}, Replacement{OffsetTarget{31, 0xcee7}, { {0, PlaySound{34, 0, {}}}, }}, Replacement{OffsetTarget{31, 0xdad3}, { {0, PlaySound{67, 0, {}}}, {1, PlaySound{67, 0, {}}}, {2, PlaySound{67, 0, {}}}, }}, Replacement{OffsetTarget{31, 0xdeae}, { {0, PlaySound{67, 0, {}}}, {1, PlaySound{67, 0, {}}}, }}, Replacement{OffsetTarget{31, 0xe182}, { {0, PlaySound{38, 0, {}}}, }}, // This is presumably intentional //Replacement{OffsetTarget{31, 0xeab2}, { // {0, GiveItem{2, 5, 50, {}}}, //}}, Replacement{OffsetTarget{31, 0xf312}, { {0, PlaySound{34, 0, {}}}, {1, PlaySound{72, 0, {}}}, {2, PlaySound{72, 0, {}}}, {3, PlaySound{72, 0, {}}}, {4, PlaySound{39, 2, {}}}, }}, Replacement{OffsetTarget{31, 0xf7f2}, { {0, PlaySound{34, 0, {}}}, {1, PlaySound{66, 1, {}}}, }}, Replacement{OffsetTarget{31, 0xfa52}, { {0, PlaySound{34, 1, {}}}, }}, Replacement{OffsetTarget{31, 0xfdbe}, { {0, PlaySound{34, 0, {}}}, }}, Replacement{OffsetTarget{31, 0x10226}, { {0, PlaySound{34, 0, {}}}, }}, Replacement{OffsetTarget{31, 0x10563}, { {0, PlaySound{67, 0, {}}}, {1, PlaySound{67, 0, {}}}, {2, PlaySound{67, 0, {}}}, {3, PlaySound{67, 0, {}}}, }}, Replacement{OffsetTarget{31, 0x112da}, { {0, PlaySound{64, 0, {}}}, {1, PlaySound{64, 0, {}}}, }}, Replacement{OffsetTarget{31, 0x11740}, { {0, PlaySound{34, 0, {}}}, }}, Replacement{OffsetTarget{31, 0x12015}, { {0, PlaySound{34, 0, {}}}, {1, PlaySound{38, 1, {}}}, }}, Replacement{OffsetTarget{31, 0x12404}, { {0, PlaySound{34, 0, {}}}, {1, PlaySound{38, 1, {}}}, }}, Replacement{OffsetTarget{31, 0x126fb}, { {0, SetFlag{0x1f03, 0, 0, 0, 1}}, {1, PlaySound{34, 0, {}}}, {2, PlaySound{34, 0, {}}}, }}, Replacement{OffsetTarget{31, 0x12921}, { {0, PlaySound{34, 0, {}}}, {1, PlaySound{34, 0, {}}}, }}, Replacement{OffsetTarget{31, 0x12a7b}, { {0, PlaySound{38, 1, {}}}, }}, Replacement{OffsetTarget{31, 0x12ea3}, { {0, PlaySound{34, 0, {}}}, {1, PlaySound{34, 0, {}}}, }}, Replacement{OffsetTarget{31, 0x12fb2}, { {0, PlaySound{34, 0, {}}}, {1, PlaySound{34, 0, {}}}, }}, Replacement{OffsetTarget{31, 0x131c6}, { {0, PlaySound{34, 0, {}}}, }}, Replacement{OffsetTarget{31, 0x140af}, { {0, PlaySound{34, 0, {}}}, }}, Replacement{OffsetTarget{31, 0x143ef}, { {0, PlaySound{34, 0, {}}}, {1, PlaySound{38, 1, {}}}, }}, Replacement{OffsetTarget{31, 0x1491e}, { {0, PlaySound{34, 0, {}}}, }}, Replacement{OffsetTarget{31, 0x14c58}, { {0, PlaySound{67, 0, {}}}, {1, PlaySound{67, 0, {}}}, {2, PlaySound{67, 0, {}}}, {3, PlaySound{67, 0, {}}}, }}, Replacement{OffsetTarget{31, 0x155af}, { {0, PlaySound{34, 0, {}}}, }}, Replacement{OffsetTarget{31, 0x15c9e}, { {0, ElapseTime{Times::ThreeHours, {}}}, {1, PlaySound{34, 0, {}}}, }}, Replacement{OffsetTarget{31, 0x16978}, { {0, PlaySound{34, 0, {}}}, }}, Replacement{OffsetTarget{31, 0x170ee}, { {0, PlaySound{34, 0, {}}}, }}, Replacement{OffsetTarget{31, 0x17bf9}, { {1, PlaySound{34, 0, {}}}, }}, Replacement{OffsetTarget{31, 0x17e15}, { {0, PlaySound{72, 1, {}}}, {1, PlaySound{72, 1, {}}}, {2, PlaySound{72, 1, {}}}, {3, PlaySound{72, 1, {}}}, {4, PlaySound{20, 2, {}}}, }}, Replacement{OffsetTarget{31, 0x17fd1}, { {0, PlaySound{72, 1, {}}}, {1, PlaySound{72, 1, {}}}, {2, PlaySound{72, 1, {}}}, {3, PlaySound{72, 1, {}}}, }}, Replacement{OffsetTarget{31, 0x18a4e}, { {0, PlaySound{34, 0, {}}}, }}, Replacement{OffsetTarget{31, 0x19328}, { {0, PlaySound{39, 2, {}}}, }}, Replacement{OffsetTarget{31, 0x1953d}, { {0, PlaySound{1007, 0, {}}}, }}, Replacement{OffsetTarget{31, 0x1955a}, { {0, PlaySound{1039, 0, {}}}, }}, Replacement{OffsetTarget{31, 0x19577}, { {0, PlaySound{1040, 0, {}}}, }}, Replacement{OffsetTarget{31, 0x1993f}, { {0, SetFlag{0xdbba, 0xff, 0x40, 0, 0}}, {1, PlaySound{1008, 0, {}}}, }}, Replacement{OffsetTarget{31, 0x19e38}, { {0, PlaySound{34, 0, {}}}, }}, Replacement{OffsetTarget{31, 0x1a438}, { {0, PlaySound{64, 0, {}}}, {1, PlaySound{64, 0, {}}}, {2, PlaySound{63, 1, {}}}, }}, Replacement{OffsetTarget{31, 0x1a7fb}, { {0, PlaySound{64, 0, {}}}, {1, PlaySound{64, 0, {}}}, }}, Replacement{OffsetTarget{31, 0x1af8f}, { {0, PlaySound{34, 0, {}}}, {1, PlaySound{38, 1, {}}}, }}, Replacement{OffsetTarget{31, 0x1b2df}, { {0, PlaySound{38, 2, {}}}, }}, Replacement{OffsetTarget{31, 0x1b3b9}, { {0, PlaySound{34, 1, {}}}, {1, PlaySound{38, 1, {}}}, }}, Replacement{OffsetTarget{31, 0x1b787}, { {0, PlaySound{34, 0, {}}}, {1, PlaySound{72, 1, {}}}, }}, Replacement{OffsetTarget{31, 0x1bb40}, { {0, PlaySound{21, 1, {}}}, {1, PlaySound{21, 1, {}}}, {2, PlaySound{21, 1, {}}}, }}, Replacement{OffsetTarget{31, 0x1d34f}, { {0, PlaySound{64, 0, {}}}, {1, PlaySound{64, 0, {}}}, }}, Replacement{OffsetTarget{31, 0x1d6a9}, { {0, PlaySound{34, 0, {}}}, }}, Replacement{OffsetTarget{31, 0x1ea01}, { {0, PlaySound{34, 0, {}}}, {1, PlaySound{38, 0, {}}}, }}, Replacement{OffsetTarget{31, 0x1eed0}, { {0, PlaySound{34, 0, {}}}, }}, Replacement{OffsetTarget{31, 0x1fd64}, { {0, PlaySound{72, 0, {}}}, {1, PlaySound{72, 0, {}}}, {2, PlaySound{72, 0, {}}}, }}, Replacement{OffsetTarget{31, 0x1fef5}, { {0, PlaySound{34, 0, {}}}, {1, PlaySound{34, 0, {}}}, }}, Replacement{OffsetTarget{31, 0x2055a}, { {0, PlaySound{64, 0, {}}}, }}, Replacement{OffsetTarget{31, 0x21269}, { {0, PlaySound{29, 1, {}}}, }}, Replacement{OffsetTarget{31, 0x219f9}, { {0, PlaySound{39, 1, {}}}, }}, Replacement{OffsetTarget{31, 0x219f9}, { {0, PlaySound{39, 1, {}}}, }}, Replacement{OffsetTarget{31, 0x21ef6}, { {0, PlaySound{34, 0, {}}}, {1, PlaySound{67, 0, {}}}, {2, PlaySound{67, 0, {}}}, }}, Replacement{OffsetTarget{31, 0x221e2}, { {0, PlaySound{38, 1, {}}}, }}, Replacement{OffsetTarget{31, 0x22c2a}, { {0, SetEndOfDialogState{-1, {}}}, {2, PlaySound{29, 2, {}}}, }}, // Fadamor's formula well... Replacement{OffsetTarget{31, 0x23986}, { {0, LoseItem{115, 1, {}}}, {2, PlaySound{63, 2, {}}}, }}, Replacement{OffsetTarget{31, 0x23da6}, { {0, PlaySound{67, 0, {}}}, {1, PlaySound{67, 0, {}}}, {2, PlaySound{34, 1, {}}}, }}, Replacement{OffsetTarget{31, 0x24332}, { {0, SetFlag{0x1f36, 0, 0, 0, 1}}, {1, GainSkill{7, SkillType::TotalHealth, -5120, -5120}}, {2, PlaySound{66, 1, {}}}, {3, PlaySound{40, 1, {}}}, }}, Replacement{OffsetTarget{31, 0x26a01}, { {4, LoseItem{62, 1, {}}}, {5, LoseItem{53, 100, {}}}, {6, PlaySound{66, 1, {}}}, {7, PlaySound{12, 1, {}}}, }}, Replacement{OffsetTarget{31, 0x28008}, { {0, PlaySound{75, 1, {}}}, }}, }; }
13,413
C++
.cpp
437
23.798627
90
0.499846
xavieran/BaKGL
39
2
32
GPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,353
sound.cpp
xavieran_BaKGL/bak/sound.cpp
#include "bak/sound.hpp" #include <cstring> #include <iostream> namespace BAK { Sound::Sound(unsigned t) : mType(t), mChannel(255), mFormat(SoundFormat::Unknown), mBuffer(), mMidiEvents() { } unsigned int Sound::GetType() const { return mType; } unsigned int Sound::GetChannel() const { return mChannel; } SoundFormat Sound::GetFormat() const { return mFormat; } FileBuffer* Sound::GetSamples() { return mBuffer.get(); } /* WAVE/RIFF tags & constants */ const uint32_t RIFF_ID = 0x46464952; const uint32_t WAVE_ID = 0x45564157; const uint32_t FMT_ID = 0x20746d66; const uint32_t DATA_ID = 0x61746164; void Sound::CreateWaveSamples(FileBuffer& buf) { buf.Skip(1); unsigned int rate = buf.GetUint16LE(); unsigned int size = buf.GetUint32LE(); buf.Skip(2); mBuffer = std::make_unique<FileBuffer>(12 + 8 + 16 + 8 + size); mBuffer->PutUint32LE(RIFF_ID); mBuffer->PutUint32LE(mBuffer->GetSize() - 8); mBuffer->PutUint32LE(WAVE_ID); mBuffer->PutUint32LE(FMT_ID); mBuffer->PutUint32LE(16); // chunk size mBuffer->PutUint16LE(1); // compression: 1 = uncompressed PCM mBuffer->PutUint16LE(1); // # mChannels mBuffer->PutUint32LE(rate); // sample rate mBuffer->PutUint32LE(rate); // average bytes per sec: sample rate * block align mBuffer->PutUint16LE(1); // block align: significant bits per sample / 8 * # mChannels mBuffer->PutUint16LE(8); // significant bits per sample mBuffer->PutUint32LE(DATA_ID); mBuffer->PutUint32LE(size); mBuffer->CopyFrom(&buf, size); mBuffer->Rewind(); } void Sound::GenerateWave() { } /* Standard MIDI File tags & constants */ const uint32_t SMF_HEADER = 0x6468544d; const uint32_t SMF_TRACK = 0x6b72544d; const uint16_t SMF_FORMAT = 0; const uint32_t SMF_HEADER_SIZE = 6; const uint16_t SMF_PPQN = 32; /* MIDI event codes */ const uint8_t MIDI_NOTE_OFF = 0x80; const uint8_t MIDI_NOTE_ON = 0x90; const uint8_t MIDI_KEY = 0xa0; const uint8_t MIDI_CONTROL = 0xb0; const uint8_t MIDI_PATCH = 0xc0; const uint8_t MIDI_CHANNEL = 0xd0; const uint8_t MIDI_PITCH = 0xe0; const uint8_t MIDI_SYSEX = 0xf0; const uint8_t MIDI_TIMING = 0xf8; const uint8_t MIDI_SEQ_START = 0xfa; const uint8_t MIDI_SEQ_CONT = 0xfb; const uint8_t MIDI_SEQ_END = 0xfc; const uint8_t MIDI_META = 0xff; /* MIDI Meta events */ const uint8_t META_SEQNUM = 0x00; const uint8_t META_TEXT = 0x01; const uint8_t META_COPYRIGHT = 0x02; const uint8_t META_TRACK = 0x03; const uint8_t META_INSTRUMENT = 0x04; const uint8_t META_LYRIC = 0x05; const uint8_t META_MARKER = 0x06; const uint8_t META_CUE = 0x07; const uint8_t META_CHANNEL = 0x20; const uint8_t META_PORT = 0x21; const uint8_t META_EOT = 0x2f; const uint8_t META_TEMPO = 0x51; const uint8_t META_SMPTE = 0x54; const uint8_t META_TIME = 0x58; const uint8_t META_KEY = 0x59; const uint8_t META_SEQDATA = 0x7f; void Sound::PutVariableLength(FileBuffer& buf, unsigned n) { unsigned int tmp = (n & 0x7f); unsigned int k = 1; while (n >>= 7) { tmp <<= 8; tmp |= ((n & 0x7f) | 0x80); k++; } while (k--) { buf.PutUint8(tmp & 0xff); tmp >>= 8; } } void Sound::CreateMidiEvents(FileBuffer& buf) { unsigned delta{}; unsigned code{}; unsigned mode{}; unsigned tick{}; buf.Skip(1); while ((mode != MIDI_SEQ_END) && !buf.AtEnd()) { delta = 0; code = buf.GetUint8(); while (code == MIDI_TIMING) { delta += 240; code = buf.GetUint8(); } delta += code; code = buf.GetUint8(); if ( ((code & 0xf0) == MIDI_NOTE_ON) || ((code & 0xf0) == MIDI_CONTROL) || ((code & 0xf0) == MIDI_PATCH) || ((code & 0xf0) == MIDI_PITCH)) { mode = code; if ((code & 0x0f) != mChannel) { throw std::runtime_error("Data corruption in sound data"); } } else if (code == MIDI_SEQ_END) { mode = code; } else { buf.Skip(-1); } if (mode != MIDI_SEQ_END) { MidiEvent me{}; memset(&me, 0, sizeof(MidiEvent)); me.data[0] = mode; switch (mode & 0xf0) { case MIDI_NOTE_ON: me.data[1] = buf.GetUint8(); me.data[2] = buf.GetUint8(); if (me.data[2] == 0) { me.data[0] = MIDI_NOTE_OFF | mChannel; } me.size = 3; break; case MIDI_CONTROL: case MIDI_PITCH: me.data[1] = buf.GetUint8(); me.data[2] = buf.GetUint8(); me.size = 3; break; case MIDI_PATCH: me.data[1] = buf.GetUint8(); me.size = 2; break; default: if (mode == MIDI_SEQ_END) { me.size = 1; } else { throw std::runtime_error("Data corruption in sound file"); } break; } tick += delta; mMidiEvents.emplace(tick, me); } } } void Sound::GenerateMidi() { unsigned int size = 0; unsigned int previousTick = 0; for (auto& [tick, me] : mMidiEvents) { me.delta = tick - previousTick; size += 1; if (me.delta >= (1 << 7)) { size += 1; } if (me.delta >= (1 << 14)) { size += 1; } if (me.delta >= (1 << 21)) { size += 1; } size += me.size; previousTick = tick; } mBuffer = std::make_unique<FileBuffer>(8 + SMF_HEADER_SIZE + 8 + size + 4); mBuffer->PutUint32LE(SMF_HEADER); mBuffer->PutUint32BE(SMF_HEADER_SIZE); mBuffer->PutUint16BE(SMF_FORMAT); mBuffer->PutUint16BE(1); mBuffer->PutUint16BE(SMF_PPQN); mBuffer->PutUint32LE(SMF_TRACK); mBuffer->PutUint32BE(size); for (const auto& [_, me] : mMidiEvents) { PutVariableLength(*mBuffer, me.delta); for (unsigned i = 0; i < me.size; i++) { mBuffer->PutUint8(me.data[i]); } } mMidiEvents.clear(); mBuffer->PutUint8(0); mBuffer->PutUint8(MIDI_META); mBuffer->PutUint8(META_EOT); mBuffer->PutUint8(0); mBuffer->Rewind(); } void Sound::AddVoice(FileBuffer& buf) { unsigned int code = buf.GetUint8(); mChannel = code & 0x0f; if (code == 0xfe) { mFormat = SoundFormat::Wave; CreateWaveSamples(buf); } else { mFormat = SoundFormat::Midi; CreateMidiEvents(buf); } } void Sound::GenerateBuffer() { if (mFormat == SoundFormat::Midi) { GenerateMidi(); } } }
7,180
C++
.cpp
261
20.942529
96
0.548593
xavieran/BaKGL
39
2
32
GPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,354
objectInfo.cpp
xavieran_BaKGL/bak/objectInfo.cpp
#include "bak/objectInfo.hpp" #include "com/assert.hpp" #include "com/logger.hpp" #include "com/ostream.hpp" #include "bak/fileBufferFactory.hpp" #include <sstream> #include <iomanip> namespace BAK { std::string_view ToString(Modifier m) { switch (m) { case Modifier::Flaming: return "Flaming"; case Modifier::SteelFire: return "Steelfired"; case Modifier::Frost: return "Frosted"; case Modifier::Enhancement1: return "Enhanced #1"; case Modifier::Enhancement2: return "Enhanced #2"; case Modifier::Blessing1: return "Blessing1"; case Modifier::Blessing2: return "Blessing2"; case Modifier::Blessing3: return "Blessing3"; default: return "Unknown Modifier"; } } Modifier ToModifier(unsigned modifierMask) { for (unsigned i = 0; i < 8; i++) { if (((1 << i) & (modifierMask >> 8)) != 0) { return static_cast<Modifier>(i); } } return Modifier::Blessing1; } std::ostream& operator<<(std::ostream& os, Modifier m) { os << ToString(m); return os; } std::string_view ToString(RacialModifier m) { switch (m) { case RacialModifier::None: return "None"; case RacialModifier::Tsurani: return "Tsurani"; case RacialModifier::Elf: return "Elf"; case RacialModifier::Human: return "Human"; case RacialModifier::Dwarf: return "Dwarf"; default: return "Unknown RacialMod"; } } std::string_view ToString(SaleCategory i) { switch (i) { case SaleCategory::Jewellery: return "Jewellery"; case SaleCategory::Utility: return "Utility"; case SaleCategory::Rations: return "Rations"; case SaleCategory::PreciousGems: return "PreciousGems"; case SaleCategory::Keys: return "Keys"; case SaleCategory::QuestItem: return "QuestItem"; case SaleCategory::Sword: return "Sword"; case SaleCategory::CrossbowRelated: return "CrossbowRelated"; case SaleCategory::Armor: return "Armor"; case SaleCategory::UsableMundaneItem: return "UsableMundaneItem"; case SaleCategory::UsableMagicalItem: return "UsableMagicalItem"; case SaleCategory::Staff: return "Staff"; case SaleCategory::Scroll: return "Scroll"; case SaleCategory::BookOrNote: return "BookOrNote"; case SaleCategory::Potions: return "Potions"; case SaleCategory::Modifier: return "Modifier"; case SaleCategory::All: return "All"; default: return "UnknownSaleCategory"; } } std::ostream& operator<<(std::ostream& os, SaleCategory cat) { os << ToString(cat); return os; } std::string_view ToString(ItemCategory i) { switch (i) { case ItemCategory::Modifier: return "Modifier"; case ItemCategory::Potion: return "Potion"; case ItemCategory::Book: return "Book"; case ItemCategory::Staff: return "Staff"; case ItemCategory::Magical: return "Magical"; case ItemCategory::Armor: return "Armor"; case ItemCategory::Crossbow: return "Crossbow"; case ItemCategory::Sword: return "Sword"; case ItemCategory::Combat: return "Combat"; case ItemCategory::Gemstones: return "Gemstones"; case ItemCategory::Rations: return "Rations"; case ItemCategory::Other: return "Other"; case ItemCategory::NonSaleable: return "NonSaleable"; case ItemCategory::Scroll: return "Scroll"; case ItemCategory::Key: return "Key"; case ItemCategory::Inn: return "Inn"; default: return "UnknownItemCategory"; } } std::ostream& operator<<(std::ostream& os, ItemCategory cat) { os << ToString(cat); return os; } std::vector<SaleCategory> GetCategories(std::uint16_t value) { auto categories = std::vector<SaleCategory>{}; if (value == 0xffff) { categories.emplace_back(SaleCategory::All); } else { for (std::uint16_t cat = 0; cat < 16; cat++) { if (((1 << cat) & value) != 0) categories.emplace_back(static_cast<SaleCategory>(1 << cat)); } } return categories; } std::string_view ToString(ItemType i) { switch (i) { case ItemType::Unspecified: return "Unspecified"; case ItemType::Sword: return "Sword"; case ItemType::Crossbow: return "Crossbow"; case ItemType::Staff: return "Staff"; case ItemType::Armor: return "Armor"; case ItemType::Key: return "Key"; case ItemType::Tool: return "Tool"; case ItemType::WeaponOil: return "WeaponOil"; case ItemType::ArmorOil: return "ArmorOil"; case ItemType::SpecialOil: return "SpecialOil"; case ItemType::Bowstring: return "Bowstring"; case ItemType::Scroll: return "Scroll"; case ItemType::Note: return "Note"; case ItemType::Book: return "Book"; case ItemType::Potion: return "Potion"; case ItemType::Restoratives: return "Restoratives"; case ItemType::ConditionModifier: return "ConditionModifier"; case ItemType::Light: return "Light"; case ItemType::Ingredient: return "Ingredient"; case ItemType::Ration: return "Ration"; case ItemType::Food: return "Food"; case ItemType::Other: return "Other"; default: return "Unknown"; } } std::ostream& operator<<(std::ostream& os, const GameObject& go) { os << "Object: { " << go.mName << std::hex << " fl: " << go.mFlags << std::dec << " imgIndex: " << go.mImageIndex << " lvl: " << go.mLevel << " val: " << go.mValue << " swing (" << go.mStrengthSwing << ", " << go.mAccuracySwing << ")" << " thrust (" << go.mStrengthThrust << ", " << go.mAccuracyThrust << ")" << " size: " << go.mImageSize << " " << ToString(go.mRace) << " " << ToString(go.mType) << " Cat: (" << std::hex << go.mCategories << std::dec << ")[" << GetCategories(go.mCategories) << "]" << " useSound: " << go.mUseSound << " times: " << go.mSoundPlayTimes << " stackSize: " << go.mStackSize << " defaultStackSize: " << go.mDefaultStackSize << " eff (" << std::hex << go.mEffectMask << ", " << std::dec << go.mEffect << " ) potionPower: " << go.mPotionPowerOrBookChance << " altEff: " << std::dec << go.mAlternativeEffect << " mod (" << std::hex << go.mModifierMask << ", " << std::dec << go.mModifier << ") df0: " << go.mDullFactor0 << " df1: " << go.mDullFactor1 << " minCond: " << go.mMinCondition << "}"; return os; } ObjectIndex::ObjectIndex() { const auto& logger = Logging::LogState::GetLogger("BAK::ObjectIndex"); auto fb = FileBufferFactory::Get().CreateDataBuffer("OBJINFO.DAT"); for (unsigned i = 0; i < sObjectCount; i++) { const auto name = fb.GetString(30); logger.Spam() << "ItemOff: " << std::hex << fb.Tell() << std::dec << "\n"; const auto unknown = fb.GetArray<2>(); const auto flags = fb.GetUint16LE(); const auto unknown2 = fb.GetArray<2>(); const auto level = fb.GetSint16LE(); const auto value = fb.GetSint16LE(); const auto strengthSwing = fb.GetSint16LE(); const auto strengthThrust = fb.GetSint16LE(); const auto accuracySwing = fb.GetSint16LE(); const auto accuracyThrust = fb.GetSint16LE(); const auto optionalImageIndex = fb.GetUint16LE(); const auto imageSize = fb.GetUint16LE(); const auto useSound = fb.GetUint8(); const auto soundPlayTimes = fb.GetUint8(); const auto stackSize = fb.GetUint8(); const auto defaultStackSize = fb.GetUint8(); const auto race = fb.GetUint16LE(); const auto categories = fb.GetUint16LE(); const auto type = fb.GetUint16LE(); const auto effectMask = fb.GetUint16LE(); const auto effect = fb.GetSint16LE(); const auto potionPowerOrBookChance = fb.GetUint16LE(); const auto alternativeEffect = fb.GetUint16LE(); const auto modifierMask = fb.GetUint16LE(); const auto modifier = fb.GetSint16LE(); const auto dullFactor0 = fb.GetUint16LE(); const auto dullFactor1 = fb.GetUint16LE(); const auto minimumCondition = fb.GetUint16LE(); mObjects[i] = GameObject{ name, flags, level, value, strengthSwing, accuracySwing, strengthThrust, accuracyThrust, optionalImageIndex != 0 ? optionalImageIndex : i, imageSize, useSound, soundPlayTimes, stackSize, defaultStackSize, static_cast<RacialModifier>(race), categories, static_cast<ItemType>(type), effectMask, effect, potionPowerOrBookChance, alternativeEffect, modifierMask, modifier, dullFactor0, dullFactor1, minimumCondition}; logger.Spam() << i << std::hex << " Unknown0: " << unknown << "|2 " << unknown2 << "|" << name << std::dec << "\n"; logger.Spam() << "ItmIndex:" << i << " " << mObjects[i] << "\n"; } while (fb.GetBytesLeft() != 0) { mScrollValues.emplace_back(Royals{fb.GetUint16LE()}); } } const ObjectIndex& ObjectIndex::Get() { static ObjectIndex objectIndex{}; return objectIndex; } const GameObject& ObjectIndex::GetObject(ItemIndex index) const { ASSERT(index.mValue < sObjectCount); return mObjects[index.mValue]; } Royals ObjectIndex::GetScrollValue(SpellIndex index) const { ASSERT(index.mValue < mScrollValues.size()); return mScrollValues[index.mValue]; } std::ostream& ShowRow(std::ostream& os, const GameObject& go) { std::stringstream ss{}; ss << std::setw(30) << std::setfill(' '); ss << go.mName; os << ss.str() << "\t" << std::hex << std::setw(4) << std::setfill('0') << go.mFlags << std::dec << "\t" << std::setw(4) << std::setfill('0') << go.mLevel << "\t" << std::setw(5) << std::setfill('0') << go.mValue << "\t(" << std::setw(2) << go.mStrengthSwing << ", " << std::setw(2) << go.mAccuracySwing << ")" << "\t(" << std::setw(2) << go.mStrengthThrust << ", " << std::setw(2) << go.mAccuracyThrust << ")" << "\t" << go.mImageSize //<< "\t" << ToString(go.mRace) << "\t" << ToString(go.mType) << "\t(" << std::hex << go.mEffectMask << ", " << go.mEffect << ")" << "\t(" << std::hex << go.mModifierMask << ", " << go.mModifier << std::dec << ")\t"; return os; } std::ostream& operator<<(std::ostream& os, const ObjectIndex& oi) { std::stringstream ss{}; ss << std::setw(30) << std::setfill(' '); ss << "Name"; os << "Number\t" << ss.str() << "\t\tFlags\tLevel\tValue\tSwing\t\tThrust\t\tSize\tEffect\tModifier\t\n"; for(unsigned i = 0; i < oi.sObjectCount; i++) { std::stringstream ss{}; ss << std::setw(3) << std::setfill('0'); ss << i << " (" << std::hex; ss << std::setw(2) << std::setfill('0'); ss << i << std::dec << ")\t"; os << ss.str(); ShowRow(os, oi.GetObject(ItemIndex{i})) << "\n"; } return os; } }
11,110
C++
.cpp
297
31.262626
109
0.616534
xavieran/BaKGL
39
2
32
GPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,355
saveManager.cpp
xavieran_BaKGL/bak/saveManager.cpp
#include "bak/saveManager.hpp" #include "bak/file/util.hpp" namespace BAK { unsigned convertToInt(const std::string& s) { std::stringstream ss{}; ss << s; unsigned index{}; ss >> index; return index; } std::string LoadSaveName(FileBuffer& fb) { fb.Seek(0); return fb.GetString(30); } std::ostream& operator<<(std::ostream& os, const SaveFile& saveFile) { os << "SaveFile{ " << saveFile.mIndex << ", " << saveFile.mName << ", " << saveFile.mPath << "}"; return os; } std::ostream& operator<<(std::ostream& os, const SaveDirectory& saveDir) { os << "SaveDir{ " << saveDir.mIndex << ", " << saveDir.mName << ", " << saveDir.mSaves.size() << "}"; return os; } SaveManager::SaveManager( const std::string& savePath) : mSavePath{savePath}, mDirectories{}, mLogger{Logging::LogState::GetLogger("BAK::SaveManager")} {} const std::vector<SaveDirectory>& SaveManager::GetSaves() const { return mDirectories; } void SaveManager::RefreshSaves() { mDirectories = MakeSaveDirectories(); } void SaveManager::RemoveDirectory(unsigned index) { mLogger.Info() << "Removing save directory: " << mDirectories.at(index) << "\n"; std::filesystem::remove_all(mSavePath / mDirectories.at(index).GetPath()); RefreshSaves(); } void SaveManager::RemoveSave(unsigned directory, unsigned save) { mLogger.Info() << "Removing save file: " << mDirectories.at(directory).mSaves.at(save).mPath << "\n"; std::filesystem::remove(mDirectories.at(directory).mSaves.at(save).mPath); RefreshSaves(); } const SaveFile& SaveManager::MakeSave( const std::string& saveDirectory, const std::string& saveName, bool isBookmark) { mLogger.Debug() << __FUNCTION__ << "(" << saveDirectory << ", " << saveName << ")" << std::endl; const auto it = std::find_if(mDirectories.begin(), mDirectories.end(), [&](const auto& elem){ return saveDirectory == elem.mName; }); auto& directory = std::invoke([&]() -> SaveDirectory& { if (it != mDirectories.end()) { mLogger.Debug() << __FUNCTION__ << " Found existing save directory: " << *it << std::endl; return *it; } else { auto directory = SaveDirectory{ static_cast<unsigned>(mDirectories.size() + 1), saveDirectory, {}}; std::filesystem::create_directory(mSavePath / directory.GetPath()); mLogger.Debug() << __FUNCTION__ << " Creating directory: " << mSavePath / directory.GetPath() << std::endl; return mDirectories.emplace_back( std::move(directory)); } }); if (isBookmark) { if (directory.mSaves.size() > 0 && directory.mSaves.begin()->GetFilename() == "SAVE00.GAM") { mLogger.Debug() << __FUNCTION__ << " Found existing bookmark: " << *it << std::endl; } else { directory.mSaves.insert(directory.mSaves.begin(), SaveFile{0, "Bookmark", ((mSavePath / directory.GetPath()) / "SAVE00.GAM").string()}); mLogger.Debug() << __FUNCTION__ << " Creating bookmark: " << *directory.mSaves.begin() << std::endl; } return *directory.mSaves.begin(); } mLogger.Debug() << __FUNCTION__ << " SaveDir: " << directory << std::endl; const auto fileIt = std::find_if(directory.mSaves.begin(), directory.mSaves.end(), [&](const auto& elem){ return saveName == elem.mName; }); if (fileIt != directory.mSaves.end()) { return *fileIt; } else { std::stringstream ss{}; unsigned saveNumber = directory.mSaves.size() + 1; ss << "SAVE" << std::setw(2) << std::setfill('0') << saveNumber << ".GAM"; return directory.mSaves.emplace_back( SaveFile{ static_cast<unsigned>(directory.mSaves.size()), saveName, ((mSavePath / directory.GetPath()) / ss.str()).string()}); } } std::vector<SaveFile> SaveManager::MakeSaveFiles(std::filesystem::path saveDir) { const auto saveSuffix = std::regex{"[Ss][Aa][Vv][Ee]([0-9]{2}).[Gg][Aa][mM]$"}; const auto saveFileDir = std::filesystem::directory_iterator{saveDir}; std::vector<SaveFile> saveFiles{}; for (const auto& save : saveFileDir) { const auto saveName = save.path().filename().string(); Logging::LogDebug(__FUNCTION__) << "Save: " << saveName << " matches: " << std::regex_search(saveName, saveSuffix) << std::endl; std::smatch matches{}; std::regex_search(saveName, matches, saveSuffix); if (matches.size() > 0) { auto fb = File::CreateFileBuffer(save.path().string()); const auto index = convertToInt(matches.str(1)); const auto name = index == 0 ? "Bookmark" : LoadSaveName(fb); saveFiles.emplace_back( SaveFile{ index, name, save.path().string()}); } } std::sort( saveFiles.begin(), saveFiles.end(), [](const auto& lhs, const auto& rhs){ return lhs.mIndex < rhs.mIndex; }); return saveFiles; } std::vector<SaveDirectory> SaveManager::MakeSaveDirectories() { std::vector<SaveDirectory> saveDirs{}; const auto gameDirectoryPath = GetBakDirectoryPath() / "GAMES"; if (!std::filesystem::exists(gameDirectoryPath)) { mLogger.Info() << "Save game directory path: [" << gameDirectoryPath << "] does not exist, creating it." << std::endl; try { std::filesystem::create_directory(gameDirectoryPath); } catch (const std::filesystem::filesystem_error& error) { mLogger.Error() << "Failed to create save game directory path: [" << gameDirectoryPath << "] " << error.what() << std::endl; } return saveDirs; } const auto saveDirectories = std::filesystem::directory_iterator{ gameDirectoryPath}; const auto dirSuffix = std::regex{".[Gg]([0-9]{2})$"}; for (const auto& directory : saveDirectories) { const auto dirName = directory.path().filename().string(); Logging::LogDebug(__FUNCTION__) << "Directory: " << dirName << " matches: " << std::regex_search(dirName, dirSuffix) << std::endl; std::smatch matches{}; std::regex_search(dirName, matches, dirSuffix); if (matches.size() > 0) { saveDirs.emplace_back( SaveDirectory{ convertToInt(matches.str(1)), directory.path().stem().string(), MakeSaveFiles(directory.path())}); } } std::sort( saveDirs.begin(), saveDirs.end(), [](const auto& lhs, const auto& rhs){ return lhs.mIndex < rhs.mIndex; }); return saveDirs; } }
7,004
C++
.cpp
191
29.193717
138
0.585175
xavieran/BaKGL
39
2
32
GPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,356
container.cpp
xavieran_BaKGL/bak/container.cpp
#include "bak/container.hpp" #include "bak/inventory.hpp" #include "com/ostream.hpp" #include <optional> namespace BAK { std::ostream& operator<<(std::ostream& os, const ContainerWorldLocation& loc) { os << "CWL { Z: " << loc.mZone << " from: " << loc.GetFrom() << " to: " << loc.GetTo() << " model: " << +loc.mModel << " unk: " << std::hex << +loc.mUnknown << std::dec << " loc: " << loc.mLocation << "}"; return os; } unsigned ContainerWorldLocation::GetFrom() const { return (mChapterRange >> 4) & 0xf; } unsigned ContainerWorldLocation::GetTo() const { return mChapterRange & 0xf; } std::ostream& operator<<(std::ostream& os, const ContainerGDSLocation& loc) { os << "CGL { arr: " << std::hex << loc.mUnknown << std::dec << " loc: " << loc.mLocation << "}"; return os; } std::ostream& operator<<(std::ostream& os, const ContainerCombatLocation& loc) { os << "CCL { arr: " << std::hex << loc.mUnknown << std::dec << " combat: " << loc.mCombat << " person: " << loc.mCombatant << "}"; return os; } std::ostream& operator<<(std::ostream& os, const ContainerLocation& loc) { return std::visit( [&](const auto& i) -> std::ostream& { return (os << i); }, loc); } std::ostream& operator<<(std::ostream& os, const ContainerHeader& header) { os << "ContainerHeader @" << std::hex << header.mAddress << std::dec << " {" << header.mLocation << " LocType: " << +header.mLocationType << " Items: " << +header.mItems << " Capacity: " << +header.mCapacity << " Flags: " << std::hex << +header.mFlags << std::dec << "}"; return os; } ContainerHeader::ContainerHeader() : mAddress{0}, mLocation{ ContainerWorldLocation{ ZoneNumber{0}, 0, 0, 0, glm::uvec2{0, 0}}}, mLocationType{0}, mItems{0}, mCapacity{0}, mFlags{0} { } ContainerHeader::ContainerHeader(ContainerWorldLocationTag, FileBuffer& fb) { mAddress = fb.Tell(); const auto zone = ZoneNumber{fb.GetUint8()}; const auto chapterRange = fb.GetUint8(); const auto model = fb.GetUint8(); const auto unknown = fb.GetUint8(); const auto x = fb.GetUint32LE(); const auto y = fb.GetUint32LE(); mLocation = ContainerWorldLocation{ zone, chapterRange, model, unknown, GamePosition{x, y}}; mLocationType = fb.GetUint8(); mItems = fb.GetUint8(); mCapacity = fb.GetUint8(); mFlags = fb.GetUint8(); } ContainerHeader::ContainerHeader(ContainerGDSLocationTag, FileBuffer& fb) { mAddress = fb.Tell(); mLocation = ContainerGDSLocation{ fb.GetArray<4>(), HotspotRef{ static_cast<std::uint8_t>(fb.GetUint32LE()), MakeHotspotChar(static_cast<char>(fb.GetUint32LE()))}}; mLocationType = fb.GetUint8(); mItems = fb.GetUint8(); mCapacity = fb.GetUint8(); mFlags = fb.GetUint8(); } ContainerHeader::ContainerHeader(ContainerCombatLocationTag, FileBuffer& fb) { mAddress = fb.Tell(); mLocation = ContainerCombatLocation{ fb.GetArray<4>(), fb.GetUint32LE(), fb.GetUint32LE()}; mLocationType = fb.GetUint8(); ASSERT(mLocationType == 7); mItems = fb.GetUint8(); mCapacity = fb.GetUint8(); mFlags = fb.GetUint8(); } ZoneNumber ContainerHeader::GetZone() const { ASSERT(std::holds_alternative<ContainerWorldLocation>(mLocation)); return std::get<ContainerWorldLocation>(mLocation).mZone; } GamePosition ContainerHeader::GetPosition() const { ASSERT(std::holds_alternative<ContainerWorldLocation>(mLocation)); return std::get<ContainerWorldLocation>(mLocation).mLocation; } HotspotRef ContainerHeader::GetHotspotRef() const { ASSERT(std::holds_alternative<ContainerGDSLocation>(mLocation)); return std::get<ContainerGDSLocation>(mLocation).mLocation; } unsigned ContainerHeader::GetCombatNumber() const { ASSERT(std::holds_alternative<ContainerCombatLocation>(mLocation)); return std::get<ContainerCombatLocation>(mLocation).mCombat; } unsigned ContainerHeader::GetCombatantNumber() const { ASSERT(std::holds_alternative<ContainerCombatLocation>(mLocation)); return std::get<ContainerCombatLocation>(mLocation).mCombatant; } unsigned ContainerHeader::GetModel() const { assert(std::holds_alternative<ContainerWorldLocation>(mLocation)); return std::get<ContainerWorldLocation>(mLocation).mModel; } bool ContainerHeader::PresentInChapter(Chapter chapter) const { if (std::holds_alternative<ContainerWorldLocation>(mLocation)) { const auto& location = std::get<ContainerWorldLocation>(mLocation); return (chapter.mValue <= location.GetTo()) && (chapter.mValue >= location.GetFrom()); } // FIXME: Double check if this applies to other container types return true; } std::ostream& operator<<(std::ostream& os, const ContainerEncounter& ce) { os << "ContainerEncounter { require: " << std::hex << ce.mRequireEventFlag << " set: " << ce.mSetEventFlag << std::dec << " hotspot: " << ce.mHotspotRef << " pos: " << ce.mEncounterPos << "}"; return os; } std::ostream& operator<<(std::ostream& os, const ContainerDialog& ce) { os << "ContainerDialog { cv: " << std::hex << +ce.mContextVar << " order: " << +ce.mDialogOrder << " dialog: " << ce.mDialog << std::dec << "}"; return os; } std::ostream& operator<<(std::ostream& os, const GenericContainer& gc) { os << "GenericContainer{ " << gc.GetHeader(); if (gc.HasLock()) os << gc.GetLock(); if (gc.HasDoor()) os << gc.GetDoor(); if (gc.HasDialog()) os << gc.GetDialog(); if (gc.HasShop()) os << gc.GetShop(); if (gc.HasEncounter()) os << gc.GetEncounter(); if (gc.HasLastAccessed()) os << std::hex << " LastAccessed: " << gc.GetLastAccessed() << std::dec; if (gc.HasInventory()) os << " " << gc.GetInventory(); os << "}"; return os; } }
6,152
C++
.cpp
179
29.418994
134
0.63641
xavieran/BaKGL
39
2
32
GPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,357
time.cpp
xavieran_BaKGL/bak/time.cpp
#include "bak/time.hpp" namespace BAK { void EffectOfConditionsWithTime( Skills& skills, Conditions& conditions, unsigned healFraction, unsigned healPercentCeiling) { unsigned conditionChangePcnt = 0; int healAmount = 0; if (healFraction != 0) { conditions.AdjustCondition( skills, BAK::Condition::Sick, -3); if (healPercentCeiling == 80) { conditionChangePcnt = 80; } else { conditionChangePcnt = 100; } healAmount = (1 * healFraction) / 0x64; if (conditions.GetCondition(Condition::Healing).Get() > 0) { healAmount *= 2; } } else { healAmount = 0; conditionChangePcnt = 100; } for (unsigned i = 0; i < 7; i++) { if (conditions.GetCondition(static_cast<Condition>(i)).Get() > 0) { // deteriorate amount int deterioration = static_cast<std::int16_t>(sConditionSkillEffect[i][0]); if (i < static_cast<unsigned>(Condition::Healing)) { if (conditions.GetCondition(Condition::Healing).Get() > 0) { auto deteriorateReduction = 2; if (i == static_cast<unsigned>(Condition::Sick)) { deteriorateReduction += 1; } deterioration -= deteriorateReduction; } } conditions.AdjustCondition(skills, static_cast<Condition>(i), deterioration); if (conditions.GetCondition(static_cast<Condition>(i)).Get() > 0) { const auto reduction = static_cast<std::int16_t>(sConditionSkillEffect[i][1]); healAmount += reduction; } } } if (healAmount != 0) { skills.ImproveSkill( conditions, SkillType::TotalHealth, static_cast<SkillChange>(conditionChangePcnt), healAmount << 8); } } void ImproveNearDeath( Skills& skills, Conditions& conditions) { const auto nearDeathValue = conditions.GetCondition(Condition::NearDeath).Get(); if (nearDeathValue == 0) { return; } const auto healing = conditions.GetCondition(Condition::Healing).Get(); auto improveAmount = ((nearDeathValue - 100) / 10) - 1; if (healing > 0) { improveAmount *= 2; } conditions.AdjustCondition(skills, Condition::NearDeath, improveAmount); } void DamageDueToLackOfSleep( Conditions& conditions, CharIndex charIndex, Skills& skills) { static constexpr std::array<int, 6> damagePerCharacter = {-2, -1, -2, -2, -2, -3}; skills.ImproveSkill( conditions, SkillType::TotalHealth, SkillChange::HealMultiplier_100, damagePerCharacter[charIndex.mValue] << 8); } }
2,972
C++
.cpp
100
20.93
94
0.570025
xavieran/BaKGL
39
2
32
GPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,358
startupFiles.cpp
xavieran_BaKGL/bak/startupFiles.cpp
#include "bak/startupFiles.hpp" #include "bak/resourceNames.hpp" #include "bak/coordinates.hpp" #include "bak/fileBufferFactory.hpp" #include "com/logger.hpp" namespace BAK { ChapterStartLocation LoadChapterStartLocation(Chapter chapter) { // Yes these are hardcoded in the game. static const std::vector<MapLocation> chapterStartLocations{ MapLocation{{116, 75}, 18}, MapLocation{{168, 147}, 18}, MapLocation{{256, 114}, 2}, MapLocation{{167, 24}, 26}, MapLocation{{234, 52}, 2}, MapLocation{{168, 148}, 2}, MapLocation{{184, 92}, 18}, MapLocation{{0, 0}, 0}, // timirianya MapLocation{{203, 128}, 2} }; std::stringstream ss{}; ss << "CHAP"; ss << chapter.mValue; ss << ".DAT"; auto fb = FileBufferFactory::Get().CreateDataBuffer(ss.str()); unsigned fileChapter = fb.GetUint16LE(); fb.Skip(4); // this is likely party gold. But it's always zero... Time timeChange = BAK::Time{fb.GetUint32LE()}; fb.Skip(6); unsigned zone = fb.GetUint8(); unsigned tileX = fb.GetUint8(); unsigned tileY = fb.GetUint8(); unsigned cellX = fb.GetUint8(); unsigned cellY = fb.GetUint8(); std::uint16_t heading = fb.GetUint16LE() / 0x100; auto pos = MakeGamePositionFromTileAndCell(glm::uvec2{tileX, tileY}, glm::uvec2{cellX, cellY}); return ChapterStartLocation{ chapterStartLocations[chapter.mValue - 1], Location{ ZoneNumber{zone}, {tileX, tileY}, GamePositionAndHeading{ pos, heading}}, timeChange}; } void LoadDetect() { auto fb = FileBufferFactory::Get().CreateDataBuffer("DETECT.DAT"); for (unsigned i = 0; i < 2; i++) { std::vector<std::uint32_t> items{}; for (unsigned i = 0; i < 43; i++) { items.emplace_back(fb.GetUint32LE()); Logging::LogDebug(__FUNCTION__) << i << " - " << items.back() << "\n"; } } Logging::LogDebug(__FUNCTION__) << "Remaining: " << fb.GetBytesLeft() << "\n"; } void LoadConfig() { auto fb = FileBufferFactory::Get().CreateDataBuffer("KRONDOR.CFG"); auto movementSize = fb.GetUint8(); auto turnSize = fb.GetUint8(); auto detail = fb.GetUint8(); auto textSpeed = fb.GetUint8(); auto soundConfiguration = fb.GetUint8(); } void LoadFilter() { auto fb = FileBufferFactory::Get().CreateDataBuffer("FILTER.DAT"); std::vector<std::uint32_t> items{}; for (unsigned i = 0; i < 4; i++) { for (unsigned i = 0; i < 43; i++) { items.emplace_back(fb.GetUint32LE()); Logging::LogDebug(__FUNCTION__) << i << " - " << items.back() << "\n"; } } Logging::LogDebug(__FUNCTION__) << "Remaining: " << fb.GetBytesLeft() << "\n"; } void LoadZoneDefDat(ZoneNumber zone) { auto zoneLabel = ZoneLabel{zone.mValue}; auto fb = FileBufferFactory::Get().CreateDataBuffer(zoneLabel.GetZoneDefault()); Logging::LogDebug(__FUNCTION__) << "Zone: " << zone.mValue << "\n"; const auto zoneType = fb.GetUint16LE(); const auto threeDParam = fb.GetUint16LE(); const auto playerPos_fieldA = fb.GetUint32LE(); const auto playerPos_fieldE = fb.GetUint16LE(); const auto horizonDisplayType = fb.GetUint16LE(); const auto groundType = fb.GetUint8(); const auto groundHeight = fb.GetUint8(); const auto minMapZoom = fb.GetUint32LE(); const auto unknown8 = fb.GetUint32LE(); const auto maxMapZoom = fb.GetUint32LE(); const auto mapZoomRate = fb.GetUint32LE(); const auto unknown11 = fb.GetUint16LE(); const auto unknown12 = fb.GetUint16LE(); const auto unknown13 = fb.GetUint32LE(); const auto unknown14 = fb.GetUint32LE(); const auto unknown15 = fb.GetUint16LE(); const auto unknown16 = fb.GetUint32LE(); const auto unknown17 = fb.GetUint32LE(); Logging::LogDebug(__FUNCTION__) << "ZoneType: " << zoneType << " 3dParam? " << threeDParam <<"\n"; Logging::LogDebug(__FUNCTION__) << "PlayerPos A: " << playerPos_fieldA << " PlayerPos E: " << playerPos_fieldE << "\n"; Logging::LogDebug(__FUNCTION__) << "HorizonAndGroundType: " << horizonDisplayType << "\n"; Logging::LogDebug(__FUNCTION__) << "GroundType: " << +groundType << " GroundHeight: " << +groundHeight << "\n"; Logging::LogDebug(__FUNCTION__) << " minMapZoom: " << minMapZoom << " ? " << unknown8 << "\n"; Logging::LogDebug(__FUNCTION__) << " maxMapZoom: " << maxMapZoom << " mapZoomRate: " << mapZoomRate << "\n"; Logging::LogDebug(__FUNCTION__) << " 11: " << unknown11 << "\n"; Logging::LogDebug(__FUNCTION__) << " 12: " << unknown12 << "\n"; Logging::LogDebug(__FUNCTION__) << " 13: " << unknown13 << " 14: " << unknown14 << "\n"; Logging::LogDebug(__FUNCTION__) << " 15: " << unknown15 << "\n"; Logging::LogDebug(__FUNCTION__) << " 16: " << unknown16 << " 17: " << unknown17 << "\n"; Logging::LogDebug(__FUNCTION__) << "Remaining: " << fb.GetBytesLeft() << "\n"; } ZoneMap LoadZoneMap(ZoneNumber zone) { auto zoneLabel = ZoneLabel{zone.mValue}; auto fb = FileBufferFactory::Get().CreateDataBuffer(zoneLabel.GetZoneMap()); Logging::LogDebug(__FUNCTION__) << "Zone: " << zone.mValue << "\n"; ZoneMap map{}; for (unsigned i = 0; i < 0x190; i++) { map[i] = fb.GetUint8(); } std::stringstream ss{}; for (unsigned x = 0; x < 50; x++) { for (unsigned y = 0; y < 50; y++) { auto val = GetMapDatTileValue(x, y, map); if (val > 0) { ss << "#";; } else { ss << "."; } } ss << "\n"; } Logging::LogDebug(__FUNCTION__) << "ZoneMap: \n" << ss.str() << "\n"; return map; } unsigned GetMapDatTileValue( unsigned x, unsigned y, const ZoneMap& mapDat) { auto mapVal = mapDat[(x << 3) + (y >> 3)]; auto mask = 1 << (y % 8); return mapVal & mask; } void LoadZoneDat(ZoneNumber zone) { auto zoneLabel = ZoneLabel{zone.mValue}; auto fb = FileBufferFactory::Get().CreateDataBuffer(zoneLabel.GetZoneDat()); Logging::LogDebug(__FUNCTION__) << "Zone: " << zone << "\n"; auto word0 = fb.GetUint16LE(); auto word1 = fb.GetUint16LE(); auto word2 = fb.GetUint16LE(); auto word3 = fb.GetUint16LE(); Logging::LogDebug(__FUNCTION__) << "Data: " << word0 << " " << word1 << " " << word2 << " " << word3 << "\n"; Logging::LogDebug(__FUNCTION__) << "Remaining:" << fb.GetBytesLeft() << "\n"; } }
6,624
C++
.cpp
171
32.824561
123
0.595738
xavieran/BaKGL
39
2
32
GPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,359
ttmRenderer.cpp
xavieran_BaKGL/bak/ttmRenderer.cpp
#include "bak/ttmRenderer.hpp" #include "bak/dialogSources.hpp" #include "bak/imageStore.hpp" #include "bak/sceneData.hpp" #include "bak/screen.hpp" #include "bak/textureFactory.hpp" #include "com/assert.hpp" #include "com/logger.hpp" #include "graphics/types.hpp" namespace BAK { TTMRenderer::TTMRenderer( std::string adsFile, std::string ttmFile) : mRunner{}, mLogger{Logging::LogState::GetLogger("BAK::TTMRenderer")} { mRunner.LoadTTM(adsFile, ttmFile); } Graphics::TextureStore TTMRenderer::RenderTTM() { while (!AdvanceAction()) {} return mRenderedFrames; } bool TTMRenderer::AdvanceAction() { mLogger.Debug() << "AdvanceAction" << "\n"; auto actionOpt = mRunner.GetNextAction(); if (!actionOpt) { return true; } auto action = *actionOpt; mLogger.Debug() << "Handle action: " << action << std::endl; std::visit( overloaded{ [&](const BAK::SlotPalette& sp){ mCurrentPaletteSlot = sp.mSlot; }, [&](const BAK::LoadPalette& p){ mPaletteSlots.erase(mCurrentPaletteSlot); mPaletteSlots.emplace(mCurrentPaletteSlot, BAK::Palette{p.mPalette}); }, [&](const BAK::SlotImage& sp){ mCurrentImageSlot = sp.mSlot; }, [&](const BAK::LoadImage& p){ auto fb = BAK::FileBufferFactory::Get().CreateDataBuffer(p.mImage); mImageSlots.erase(mCurrentImageSlot); mImageSlots.emplace(mCurrentImageSlot, BAK::LoadImages(fb)); mLogger.Debug() << "Loaded image: " << p.mImage << " to slot: " << mCurrentImageSlot << " has " << mImageSlots.at(mCurrentImageSlot).mImages.size() << " images\n"; }, [&](const BAK::LoadScreen& p){ auto fb = BAK::FileBufferFactory::Get().CreateDataBuffer(p.mScreenName); mScreen = BAK::LoadScreenResource(fb); }, [&](const BAK::DrawScreen& sa){ if (sa.mArg1 == 3 || sa.mArg2 == 3) { mRenderer.GetSavedImagesLayer0() = {320, 200}; mRenderer.GetSavedImagesLayer1() = {320, 200}; mRenderer.GetSavedImagesLayerBG() = {320, 200}; } if (mScreen && mPaletteSlots.contains(mCurrentPaletteSlot)) { mRenderer.RenderSprite( *mScreen, mPaletteSlots.at(mCurrentPaletteSlot).mPaletteData, glm::ivec2{0, 0}, false, mRenderer.GetForegroundLayer()); } }, [&](const BAK::DrawSprite& sa){ const auto imageSlot = sa.mImageSlot; assert(mImageSlots.contains(sa.mImageSlot)); assert(static_cast<unsigned>(sa.mSpriteIndex) < mImageSlots.at(sa.mImageSlot).mImages.size()); mRenderer.RenderSprite( mImageSlots.at(sa.mImageSlot).mImages[sa.mSpriteIndex], mPaletteSlots.at(mCurrentPaletteSlot).mPaletteData, glm::ivec2{sa.mX, sa.mY}, sa.mFlippedInY, mRenderer.GetForegroundLayer()); }, [&](const BAK::Update& sr){ RenderFrame(); }, [&](const BAK::SaveImage& si){ mRenderer.SaveImage(si.pos, si.dims, mImageSaveLayer); }, [&](const BAK::SetSaveLayer& ssl){ mImageSaveLayer = ssl.mLayer; }, [&](const BAK::SaveRegionToLayer& si){ mClearRegions.emplace(mImageSaveLayer, si); mSaves.emplace(mImageSaveLayer, mRenderer.SaveImage(si.pos, si.dims, mImageSaveLayer)); }, [&](const BAK::DrawSavedRegion& si){ const auto& clearRegion = mClearRegions.at(si.mLayer); const auto& texture = mSaves.at(si.mLayer); mRenderer.RenderTexture(texture, clearRegion.pos, mRenderer.GetForegroundLayer()); }, [&](const BAK::SaveBackground&){ mRenderer.GetSavedImagesLayer0() = {320, 200}; mRenderer.GetSavedImagesLayer1() = {320, 200}; mRenderer.SaveImage({0, 0}, {320, 200}, 2); }, [&](const BAK::DrawRect& sr){ if (!mPaletteSlots.contains(mCurrentPaletteSlot)) { // what to do in this scenario..? return; } mRenderer.DrawRect( sr.mPos, sr.mDims, mPaletteSlots.at(mCurrentPaletteSlot).mPaletteData, mRenderer.GetForegroundLayer()); }, [&](const BAK::ClipRegion& a){ mRenderer.SetClipRegion(a); }, [&](const BAK::DisableClipRegion&){ mRenderer.ClearClipRegion(); }, [&](const BAK::SetColors& sc){ mRenderer.SetColors(sc.mForegroundColor, sc.mBackgroundColor); }, [&](const BAK::Purge&){ assert(false); }, [&](const BAK::GotoTag& sa){ assert(false); }, [&](const auto& a){ Logging::LogInfo(__FUNCTION__) << "Unhandled action: " << a << "\n"; } }, action ); return false; } void TTMRenderer::RenderFrame() { if (mScreen) { mRenderer.RenderSprite( *mScreen, mPaletteSlots.at(mCurrentPaletteSlot).mPaletteData, glm::ivec2{0, 0}, false, mRenderer.GetBackgroundLayer()); } mRenderer.RenderTexture( mRenderer.GetSavedImagesLayerBG(), glm::ivec2{0}, mRenderer.GetBackgroundLayer()); mRenderer.RenderTexture( mRenderer.GetSavedImagesLayer0(), glm::ivec2{0}, mRenderer.GetBackgroundLayer()); mRenderer.RenderTexture( mRenderer.GetSavedImagesLayer1(), glm::ivec2{0}, mRenderer.GetBackgroundLayer()); mRenderer.RenderTexture( mRenderer.GetForegroundLayer(), glm::ivec2{0, 0}, mRenderer.GetBackgroundLayer()); auto bg = mRenderer.GetBackgroundLayer(); bg.Invert(); mRenderedFrames.AddTexture(bg); mRenderer.GetForegroundLayer() = Graphics::Texture{320, 200}; mRenderer.GetBackgroundLayer() = Graphics::Texture{320, 200}; } }
6,649
C++
.cpp
175
26.228571
103
0.544047
xavieran/BaKGL
39
2
32
GPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,360
chapterTransitions.cpp
xavieran_BaKGL/bak/chapterTransitions.cpp
#include "bak/chapterTransitions.hpp" #include "bak/constants.hpp" #include "bak/coordinates.hpp" #include "bak/dialogAction.hpp" #include "bak/dialogSources.hpp" #include "bak/gameState.hpp" #include "bak/hotspotRef.hpp" #include "bak/itemNumbers.hpp" #include "bak/itemInteractions.hpp" #include "bak/objectInfo.hpp" #include "bak/startupFiles.hpp" #include "bak/state/event.hpp" #include "bak/state/money.hpp" namespace BAK { std::optional<BAK::Teleport> TransitionToChapter(Chapter chapter, GameState& gs) { Logging::LogInfo(__FUNCTION__) << "Chapter: " << chapter << "\n"; gs.SetChapter(chapter); const auto startLocation = LoadChapterStartLocation(chapter); gs.SetLocation(startLocation.mLocation); gs.SetMapLocation(startLocation.mMapLocation); auto time = gs.GetWorldTime().GetTime() + Times::OneDay; time -= Time{(time.mTime % Times::OneDay.mTime)}; time += startLocation.mTimeElapsed; gs.GetWorldTime().SetTime(time); gs.GetWorldTime().SetTimeLastSlept(gs.GetWorldTime().GetTime()); if (chapter != Chapter{1}) { // combatCompleted = 1; gs.Apply(State::WritePartyMoney, chapter, gs.GetParty().GetGold()); } // is this even right....? for (unsigned i = 0; i < 80; i++) { gs.ReduceAndEvaluateTimeExpiringState(Time{0x7530}); } // Set all encounter unique state flags back to false for (unsigned i = 0; i < 0x12c0; i++) { gs.Apply(State::SetEventFlagFalse, 0x190 + i); } switch (chapter.mValue) { case 1: break; case 2: { auto* lockysRoom = gs.GetContainerForGDSScene(HotspotRef{2, 'B'}); assert(lockysRoom); auto& locky = gs.GetParty().GetCharacter(Locklear); lockysRoom->GetInventory().GetItems().clear(); lockysRoom->GetInventory().CopyFrom(locky.GetInventory()); } break; case 3: { gs.SetEventValue(0x1fbc, 0); } break; case 4: { auto* owynChest = gs.GetWorldContainer(ZoneNumber{12}, GamePosition{694800, 700800}); assert(owynChest); auto& owyn = gs.GetParty().GetCharacter(Owyn); owynChest->GetInventory().CopyFrom(owyn.GetInventory()); owyn.GetInventory().GetItems().clear(); auto torch = InventoryItemFactory::MakeItem(sTorch, 6); owyn.GiveItem(torch); auto* gorathChest = gs.GetWorldContainer(ZoneNumber{12}, GamePosition{698400, 696800}); assert(gorathChest); auto& gorath = gs.GetParty().GetCharacter(Gorath); gorathChest->GetInventory().CopyFrom(gorath.GetInventory()); gorath.GetInventory().GetItems().clear(); gorath.GiveItem(torch); UseItem(gs, gorath, InventoryIndex{0}); gs.GetParty().SetMoney(Royals{0}); } break; case 5: { auto* locklearCh5Inventory = gs.GetWorldContainer(ZoneNumber{0}, {10, 0}); assert(locklearCh5Inventory); auto& locky = gs.GetParty().GetCharacter(Locklear); locky.GetInventory().GetItems().clear(); locky.GetInventory().CopyFrom(locklearCh5Inventory->GetInventory()); { auto it = locky.GetInventory().FindItemType(BAK::ItemType::Sword); assert(it != locky.GetInventory().GetItems().end()); it->SetEquipped(true); } { auto it = locky.GetInventory().FindItemType(BAK::ItemType::Armor); assert(it != locky.GetInventory().GetItems().end()); it->SetEquipped(true); } { auto it = locky.GetInventory().FindItemType(BAK::ItemType::Crossbow); assert(it != locky.GetInventory().GetItems().end()); it->SetEquipped(true); } gs.GetParty().SetMoney(gs.Apply(State::ReadPartyMoney, Chapter{4})); } break; case 6: { // This is for the Lurough quest auto* refInn1 = gs.GetWorldContainer(ZoneNumber{0}, {20, 1}); assert(refInn1); auto* inn1 = gs.GetContainerForGDSScene(HotspotRef{60, 'C'}); assert(inn1); inn1->GetInventory().GetItems().clear(); inn1->GetInventory().CopyFrom(refInn1->GetInventory()); auto* refInn2 = gs.GetWorldContainer(ZoneNumber{0}, {30, 1}); assert(refInn2); auto* inn2 = gs.GetContainerForGDSScene(HotspotRef{64, 'C'}); assert(inn2); inn2->GetInventory().GetItems().clear(); inn2->GetInventory().CopyFrom(refInn2->GetInventory()); gs.GetParty().SetMoney(gs.Apply(State::ReadPartyMoney, Chapter{5})); } break; case 7: gs.GetParty().SetMoney(gs.Apply(State::ReadPartyMoney, Chapter{6})); gs.SetEventValue(0x1ab1, 1); break; case 8: gs.GetParty().SetMoney(gs.Apply(State::ReadPartyMoney, Chapter{7})); case 9: default: break; } gs.GetParty().ForEachActiveCharacter([](auto& character){ auto& skills = character.GetSkills(); auto& conditions = character.GetConditions(); for (unsigned i = 0; i < Conditions::sNumConditions; i++) { conditions.AdjustCondition(skills, static_cast<Condition>(i), -100); } DoAdjustHealth(skills, conditions, 100, 0x7fff); for (unsigned i = 0; i < 16; i++) { skills.GetSkill(static_cast<SkillType>(i)).mUnseenImprovement = false; } return Loop::Continue; }); // Evaluate the start of chapter actions const auto& ds = DialogStore::Get(); auto startOfChapter = ds.GetSnippet(DialogSources::mStartOfChapterActions); Logging::LogInfo(__FUNCTION__) << "Evaluating snippet: " << startOfChapter << "\n"; assert(startOfChapter.GetChoices().size() == 1); auto startOfChapterFlagsReset = ds.GetSnippet(startOfChapter.GetChoices()[0].mTarget); for (const auto& action : startOfChapterFlagsReset.GetActions()) { gs.EvaluateAction(action); } assert(startOfChapter.GetActions().size() == 1); auto* chapterActions = &ds.GetSnippet( ds.GetSnippet(std::get<PushNextDialog>(startOfChapter.mActions[0]).mTarget).GetChoices()[chapter.mValue - 1].mTarget); auto* prevActions = chapterActions; std::optional<BAK::Teleport> teleport{}; auto CheckTeleport = [&](const auto& action) { if (std::holds_alternative<BAK::Teleport>(action)) { assert(!teleport); teleport = std::get<BAK::Teleport>(action); } }; do { Logging::LogInfo(__FUNCTION__) << "Evaluating snippet: " << *chapterActions << "\n"; prevActions = chapterActions; for (const auto& action : chapterActions->GetActions()) { gs.EvaluateAction(action); CheckTeleport(action); } for (const auto& choice : chapterActions->GetChoices()) { if (gs.EvaluateDialogChoice(choice)) { chapterActions = &ds.GetSnippet(choice.mTarget); } } } while (!chapterActions->GetChoices().empty()); if (prevActions != chapterActions) { Logging::LogInfo(__FUNCTION__) << "Evaluating final actions for snippet: " << *chapterActions << "\n"; for (const auto& action : chapterActions->GetActions()) { gs.EvaluateAction(action); CheckTeleport(action); } } return teleport; } }
7,731
C++
.cpp
191
31.251309
126
0.606404
xavieran/BaKGL
39
2
32
GPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,361
layout.cpp
xavieran_BaKGL/bak/layout.cpp
#include "bak/layout.hpp" #include "com/assert.hpp" #include "bak/fileBufferFactory.hpp" namespace BAK { Layout::Layout( const std::string& path) : mIsPopup{false}, mPosition{}, mDimensions{}, mOffset{}, mWidgets{} { auto fb = FileBufferFactory::Get().CreateDataBuffer(path); fb.Skip(2); mIsPopup = (fb.GetSint16LE() != 0); fb.Skip(2); const auto xPos = fb.GetSint16LE(); const auto yPos = fb.GetSint16LE(); mPosition = glm::vec2{xPos, yPos}; const auto width = fb.GetSint16LE(); const auto height = fb.GetSint16LE(); mDimensions = glm::vec2{width, height}; fb.Skip(2); const auto xOff = fb.GetSint16LE(); const auto yOff = fb.GetSint16LE(); mOffset = glm::vec2{xOff, yOff}; fb.Skip(8); const auto numWidgets = fb.GetUint16LE(); std::vector<int> stringOffsets; stringOffsets.reserve(numWidgets); for (unsigned i = 0; i < numWidgets; i++) { auto pos = fb.GetBytesDone(); const auto widget = fb.GetUint16LE(); const auto action = fb.GetSint16LE(); const auto isVisible = fb.GetUint8() > 0; fb.Skip(2); fb.Skip(2); fb.Skip(2); const auto xPos = fb.GetSint16LE(); const auto yPos = fb.GetSint16LE(); const auto width = fb.GetUint16LE(); const auto height = fb.GetUint16LE(); fb.Skip(2); stringOffsets.emplace_back(fb.GetSint16LE()); const auto teleport = fb.GetSint16LE(); const auto image = fb.GetUint16LE(); fb.Skip(2); const auto group = fb.GetUint16LE(); fb.Skip(2); mWidgets.emplace_back( widget, action, isVisible, glm::vec2{xPos, yPos}, glm::vec2{width, height}, teleport, (image >> 1) + (image & 1), group, ""); } fb.Skip(2); const auto stringStart = fb.GetBytesDone(); for (unsigned i = 0; i < numWidgets; i++) { if (stringOffsets[i] >= 0) { fb.Seek(stringStart + stringOffsets[i]); mWidgets[i].mLabel = fb.GetString(); } } } const Layout::LayoutWidget& Layout::GetWidget(unsigned index) const { ASSERT(index < mWidgets.size()); return mWidgets[index]; } glm::vec2 Layout::GetWidgetLocation(unsigned index) const { return mPosition + mOffset + GetWidget(index).mPosition; } glm::vec2 Layout::GetWidgetDimensions(unsigned index) const { return GetWidget(index).mDimensions; } }
2,556
C++
.cpp
87
22.931034
67
0.607274
xavieran/BaKGL
39
2
32
GPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,362
itemInteractions.cpp
xavieran_BaKGL/bak/itemInteractions.cpp
#include "bak/itemInteractions.hpp" #include "bak/bard.hpp" #include "bak/dialogSources.hpp" #include "bak/gameState.hpp" #include "bak/itemNumbers.hpp" #include "bak/timeExpiringState.hpp" #include "bak/skills.hpp" #include "bak/sounds.hpp" #include "bak/state/item.hpp" #include "bak/state/event.hpp" #include "bak/state/offsets.hpp" #include "com/logger.hpp" #include "com/random.hpp" namespace BAK { ItemUseResult RepairItem( Character& character, InventoryIndex sourceItemIndex, InventoryIndex targetItemIndex) { auto& sourceItem = character.GetInventory().GetAtIndex(sourceItemIndex); auto& targetItem = character.GetInventory().GetAtIndex(targetItemIndex); if (!targetItem.IsItemType(static_cast<ItemType>(sourceItem.GetObject().mEffectMask))) { return ItemUseResult{ std::nullopt, sourceItem.GetItemIndex().mValue, DialogSources::mItemUseFailure}; } if (!targetItem.IsRepairable()) { return ItemUseResult{ std::nullopt, std::nullopt, DialogSources::mCantRepairItemFurther}; } const auto whichSkill = targetItem.IsItemType(ItemType::Armor) ? SkillType::Armorcraft : SkillType::Weaponcraft; const auto skill = character.GetSkill(whichSkill); character.ImproveSkill(whichSkill, SkillChange::ExercisedSkill, 1); const auto initialCondition = targetItem.GetCondition(); const auto adjustment = ((100 - initialCondition) * skill) / 100; auto finalCondition = initialCondition + adjustment; if (finalCondition > 99) finalCondition = 99; targetItem.SetCondition(finalCondition); targetItem.SetRepairable(false); auto result = ItemUseResult{ sourceItem.GetItemUseSound(), std::nullopt, KeyTarget{0}}; if (targetItem.IsItemType(BAK::ItemType::Crossbow)) { character.GetInventory().RemoveItem(sourceItemIndex, 1); } else { character.GetInventory().RemoveItem(sourceItemIndex, 1); } return result; } ItemUseResult FixCrossbow( Character& character, InventoryIndex sourceItemIndex, InventoryIndex targetItemIndex) { auto& sourceItem = character.GetInventory().GetAtIndex(sourceItemIndex); auto& targetItem = character.GetInventory().GetAtIndex(targetItemIndex); const auto isHeavyCrossbow = targetItem.GetItemIndex() == sTsuraniHeavyCrossbow || targetItem.GetItemIndex() == sBessyMauler; if ((sourceItem.GetItemIndex() == sLightBowstring && !isHeavyCrossbow) || (sourceItem.GetItemIndex() == sHeavyBowstring && isHeavyCrossbow)) { targetItem.SetBroken(false); targetItem.SetRepairable(false); targetItem.SetCondition(100); auto result = ItemUseResult{ sourceItem.GetItemUseSound(), std::nullopt, KeyTarget{0}}; character.GetInventory().RemoveItem(sourceItemIndex, 1); return result; } else { return ItemUseResult{ std::nullopt, std::nullopt, Target{DialogSources::mGenericCantUseItem}}; } } ItemUseResult ModifyItem( Character& character, InventoryIndex sourceItemIndex, InventoryIndex targetItemIndex) { auto& sourceItem = character.GetInventory().GetAtIndex(sourceItemIndex); auto& targetItem = character.GetInventory().GetAtIndex(targetItemIndex); if (!targetItem.IsModifiableBy(sourceItem.GetObject().mType)) { return ItemUseResult{ std::nullopt, sourceItem.GetItemIndex().mValue, DialogSources::mItemUseFailure}; } targetItem.ClearTemporaryModifiers(); targetItem.SetStatusAndModifierFromMask(sourceItem.GetObject().mEffectMask); auto result = ItemUseResult{ sourceItem.GetItemUseSound(), sourceItem.GetItemIndex().mValue, DialogSources::mItemUseSucessful}; if (sourceItem.IsChargeBased() || sourceItem.IsQuantityBased()) { character.GetInventory().RemoveItem(sourceItemIndex, 1); } return result; } ItemUseResult PoisonQuarrel( Character& character, InventoryIndex sourceItemIndex, InventoryIndex targetItemIndex) { auto& sourceItem = character.GetInventory().GetAtIndex(sourceItemIndex); auto& targetItem = character.GetInventory().GetAtIndex(targetItemIndex); Logging::LogDebug(__FUNCTION__) << " Poison Quarrel " << targetItem << " with " << sourceItem << "\n"; const auto newQuarrels = InventoryItemFactory::MakeItem( ItemIndex{targetItem.GetItemIndex().mValue + sPoisonOffset}, targetItem.GetQuantity()); auto result = ItemUseResult{ sourceItem.GetItemUseSound(), std::nullopt, KeyTarget{0}}; if (sourceItem.IsChargeBased() || sourceItem.IsQuantityBased()) { character.GetInventory().RemoveItem(sourceItemIndex, 1); } character.GetInventory().ReplaceItem(targetItemIndex, newQuarrels); return result; } bool IsPoisonableQuarrel(const InventoryItem& item) { const auto index = item.GetItemIndex().mValue; return index >= sQuarrels.mValue && index <= sTsuraniQuarrels.mValue; } ItemUseResult PoisonRations( Character& character, InventoryIndex sourceItemIndex, InventoryIndex targetItemIndex) { auto& sourceItem = character.GetInventory().GetAtIndex(sourceItemIndex); auto& targetItem = character.GetInventory().GetAtIndex(targetItemIndex); Logging::LogDebug(__FUNCTION__) << " Poison Rations " << targetItem << " with " << sourceItem << "\n"; const auto newRations = InventoryItemFactory::MakeItem( sPoisonedRations, targetItem.GetQuantity()); auto result = ItemUseResult{ sourceItem.GetItemUseSound(), std::nullopt, KeyTarget{0}}; if (sourceItem.IsChargeBased() || sourceItem.IsQuantityBased()) { character.GetInventory().RemoveItem(sourceItemIndex, 1); } character.GetInventory().ReplaceItem(targetItemIndex, newRations); return result; } ItemUseResult MakeGuardaRevanche( Character& character, InventoryIndex sourceItemIndex, InventoryIndex targetItemIndex) { auto& sourceItem = character.GetInventory().GetAtIndex(sourceItemIndex); auto& targetItem = character.GetInventory().GetAtIndex(targetItemIndex); Logging::LogDebug(__FUNCTION__) << " Make Guarda Revanche " << targetItem << " with " << sourceItem << "\n"; const auto guardaRevanche = InventoryItemFactory::MakeItem( sGuardaRevanche, 100); auto result = ItemUseResult{ // Maybe a different sound? std::make_pair(sTeleportSound, 0), sourceItem.GetItemIndex().mValue, DialogSources::mItemUseSucessful}; character.GetInventory().RemoveItem(sourceItemIndex); character.GetInventory().RemoveItem(targetItemIndex); character.GiveItem(guardaRevanche); return result; } ItemUseResult ApplyItemTo( Character& character, InventoryIndex sourceItemIndex, InventoryIndex targetItemIndex) { auto& sourceItem = character.GetInventory().GetAtIndex(sourceItemIndex); auto& targetItem = character.GetInventory().GetAtIndex(targetItemIndex); if (sourceItem.IsRepairItem()) { Logging::LogDebug(__FUNCTION__) << " Repair " << targetItem << " with " << sourceItem << "\n"; return RepairItem(character, sourceItemIndex, targetItemIndex); } else if (sourceItem.IsItemModifier() && sourceItem.GetItemIndex() != sColtariPoison && !IsPoisonableQuarrel(targetItem)) { // If incompatible item, dialog mItemUseFailure for modifiers Logging::LogDebug(__FUNCTION__) << " Modify item " << targetItem << " with " << sourceItem << "\n"; return ModifyItem(character, sourceItemIndex, targetItemIndex); } else if ((sourceItem.IsItemModifier() && sourceItem.GetObject().mEffectMask & 0x80) && IsPoisonableQuarrel(targetItem)) { Logging::LogDebug(__FUNCTION__) << " Poison quarrel " << targetItem << " with " << sourceItem << "\n"; return PoisonQuarrel(character, sourceItemIndex, targetItemIndex); } else if (sourceItem.IsItemType(ItemType::Bowstring) && targetItem.IsItemType(ItemType::Crossbow)) { Logging::LogDebug(__FUNCTION__) << " Fix Crossbow " << targetItem << " with " << sourceItem << "\n"; return FixCrossbow(character, sourceItemIndex, targetItemIndex); } else if (sourceItem.GetItemIndex() == sColtariPoison && targetItem.GetItemIndex() == sRations) { Logging::LogDebug(__FUNCTION__) << " Poison rations " << targetItem << " with " << sourceItem << "\n"; return PoisonRations(character, sourceItemIndex, targetItemIndex); } else if (sourceItem.GetItemIndex() == sEliaemsShell && targetItem.GetItemIndex() == sExoticSword) { Logging::LogDebug(__FUNCTION__) << " Make Guarda Revanche" << targetItem << " with " << sourceItem << "\n"; return MakeGuardaRevanche(character, sourceItemIndex, targetItemIndex); } else { Logging::LogDebug(__FUNCTION__) << " DO NOTHING " << targetItem << " with " << sourceItem << "\n"; } return ItemUseResult{ std::nullopt, std::nullopt, KeyTarget{0}}; } ItemUseResult ReadBook( GameState& gameState, Character& character, InventoryIndex inventoryIndex) { auto& item = character.GetInventory().GetAtIndex(inventoryIndex); if (item.GetQuantity() == 0) { return ItemUseResult{ std::nullopt, std::nullopt, KeyTarget{DialogSources::mItemHasNoCharges} }; } auto& object = item.GetObject(); assert(object.mEffectMask != 0); bool haveReadBefore = State::ReadItemHasBeenUsed( gameState, character.mCharacterIndex.mValue, item.GetItemIndex().mValue); std::optional<std::pair<SkillChange, unsigned>> improvement; if (haveReadBefore) { auto chance = GetRandomNumber(0, 0xfff) % 0x64; if (chance > object.mPotionPowerOrBookChance) { improvement = std::make_pair(SkillChange::DifferenceOfSkill, object.mAlternativeEffect); } } else { gameState.Apply( State::SetItemHasBeenUsed, character.mCharacterIndex.mValue, item.GetItemIndex().mValue); improvement = std::make_pair(SkillChange::Direct, static_cast<unsigned>(object.mEffect) << 8); } if (improvement) { auto [skillChange, amount] = *improvement; for (unsigned i = 0; i < 0x10; i++) { auto skill = static_cast<SkillType>(i); if (CheckBitSet(object.mEffectMask, skill)) { character.ImproveSkill(skill, skillChange, amount); } } } item.SetQuantity(item.GetQuantity() - 1); return ItemUseResult{ std::nullopt, item.GetItemIndex().mValue, DialogSources::mItemUseSucessful}; } ItemUseResult LearnSpell( Character& character, InventoryIndex inventoryIndex) { auto& item = character.GetInventory().GetAtIndex(inventoryIndex); assert(character.IsSpellcaster() && item.IsMagicUserOnly()); if (character.GetSpells().HaveSpell(item.GetSpell())) { return ItemUseResult{ std::nullopt, item.GetItemIndex().mValue, BAK::DialogSources::mItemUseFailure }; } else { auto sound = item.GetItemUseSound(); auto itemIndex = item.GetItemIndex(); character.GetSpells().SetSpell(item.GetSpell()); character.GetInventory().RemoveItem(inventoryIndex); return ItemUseResult{ sound, itemIndex.mValue, BAK::DialogSources::mItemUseSucessful }; } } ItemUseResult PractiseBarding( Character& character, InventoryIndex inventoryIndex) { auto& item = character.GetInventory().GetAtIndex(inventoryIndex); auto bardSkill = character.GetSkill(SkillType::Barding); const auto ClassifyBardSkill = [](auto bardSkill) { if (bardSkill < 80) { if (bardSkill < 65) { if (bardSkill < 45) { return Bard::BardStatus::Failed; } else { return Bard::BardStatus::Poor; } } else { return Bard::BardStatus::Good; } } else { return Bard::BardStatus::Best; } }; unsigned bardSong = Bard::GetSong(ClassifyBardSkill(bardSkill)); auto improvement = 0x28 + (GetRandomNumber(0, 0xfff) % 120); character.ImproveSkill(SkillType::Barding, SkillChange::Direct, improvement); auto itemIndex = item.GetItemIndex().mValue; character.GetInventory().RemoveItem(inventoryIndex, 1); return ItemUseResult{ //std::make_pair(bardSong, 1), std::nullopt, itemIndex, DialogSources::mItemUseSucessful }; } ItemUseResult UseConditionModifier( Character& character, InventoryIndex inventoryIndex) { auto& item = character.GetInventory().GetAtIndex(inventoryIndex); if (item.GetQuantity() == 0) { return ItemUseResult{ std::nullopt, 1, KeyTarget{DialogSources::mItemHasNoCharges} }; } character.GetConditions().AdjustCondition( character.GetSkills(), static_cast<BAK::Condition>(item.GetObject().mEffectMask), item.GetObject().mEffect); auto itemIndex = item.GetItemIndex().mValue; if (item.IsConsumable()) { character.GetInventory().RemoveItem(inventoryIndex, 1); } else { item.SetQuantity(item.GetQuantity() - 1); } return ItemUseResult{ item.GetItemUseSound(), itemIndex, DialogSources::mItemUseSucessful }; } ItemUseResult CurePoisoned( Character& character, InventoryIndex inventoryIndex) { auto& item = character.GetInventory().GetAtIndex(inventoryIndex); if (character.GetConditions().GetCondition(BAK::Condition::Poisoned).Get() == 0) { return ItemUseResult{ item.GetItemUseSound(), item.GetItemIndex().mValue, DialogSources::mItemUseFailure }; } character.GetConditions().AdjustCondition( character.GetSkills(), BAK::Condition::Poisoned, -100); auto itemIndex = item.GetItemIndex().mValue; character.GetInventory().RemoveItem(inventoryIndex, 1); return ItemUseResult{ item.GetItemUseSound(), std::nullopt, DialogSources::mConsumeAntiVenom }; } ItemUseResult UseRestoratives( Character& character, InventoryIndex inventoryIndex) { auto& item = character.GetInventory().GetAtIndex(inventoryIndex); const int adjustAmount = -5; for (unsigned i = 0; i < 7; i++) { auto cond = static_cast<BAK::Condition>(i); if (cond == BAK::Condition::Healing) { continue; } character.GetConditions().AdjustCondition( character.GetSkills(), cond, adjustAmount); } const auto healthRecoverAmount = item.GetObject().mEffectMask + GetRandomNumber(0, 0xfff) % 2; character.GetSkills().ImproveSkill( character.GetConditions(), SkillType::TotalHealth, SkillChange::HealMultiplier_100, healthRecoverAmount << 8); auto result = ItemUseResult{ item.GetItemUseSound(), item.GetItemIndex().mValue, DialogSources::mItemUseSucessful}; character.GetInventory().RemoveItem(inventoryIndex, 1); return result; } ItemUseResult UseTorchOrRingOfPrandur( GameState& gameState, Character& character, InventoryIndex inventoryIndex) { auto& item = character.GetInventory().GetAtIndex(inventoryIndex); if (item.IsActivated()) { auto& storage = gameState.GetTimeExpiringState(); for (unsigned i = 0; i < storage.size(); i++) { auto& state = storage[i]; if (state.mType == ExpiringStateType::Light && state.mData == 0) { state.mDuration = Time{0}; } } item.SetActivated(false); item.SetQuantity(item.GetQuantity() - 1); gameState.ReduceAndEvaluateTimeExpiringState(Time{0}); if (item.IsConsumable() && item.GetQuantity() == 0) { character.GetInventory().RemoveItem(inventoryIndex); } return ItemUseResult{ std::nullopt, std::nullopt, KeyTarget{0}}; } if (gameState.HaveActiveLightSource()) { return ItemUseResult{ std::nullopt, item.GetItemIndex().mValue, DialogSources::mItemUseFailure}; } else if (item.GetItemIndex() == sTorch && gameState.GetChapter() == Chapter{4} && gameState.GetZone() == ZoneNumber{11}) { return ItemUseResult{ std::nullopt, item.GetItemIndex().mValue, BAK::DialogSources::mLitTorchInNapthaCaverns}; } item.SetActivated(true); const auto duration = Times::OneHour * item.GetObject().mEffectMask; auto* state = AddLightTimeExpiringState(gameState.GetTimeExpiringState(), 0, duration); if (state) { gameState.RecalculatePalettesForPotionOrSpellEffect(*state); } else { assert(false); } return ItemUseResult{ item.GetItemUseSound(), item.GetItemIndex().mValue, DialogSources::mItemUseSucessful}; } ItemUseResult UseCupOfRlnnSkrr( GameState& gameState, const InventoryItem& item) { const auto pugIndex = gameState.GetParty().FindActiveCharacter(Pug); if (!pugIndex) { return ItemUseResult{ std::nullopt, item.GetItemIndex().mValue, DialogSources::mItemUseFailure}; } auto& pug = gameState.GetParty().GetCharacter(*pugIndex); auto randomSpell = SpellIndex{GetRandomNumber(0, 0xfff) % 0x2d}; if (pug.GetSpells().HaveSpell(randomSpell)) { randomSpell = SpellIndex{GetRandomNumber(0, 0xfff) % 0x2d}; } //contextVar_753b_value = learnedSpell pug.GetSpells().SetSpell(randomSpell); auto& owyn = gameState.GetParty().GetCharacter(Owyn); const auto pugSpells = pug.GetSpells().GetSpellBytes(); const auto owynSpells = owyn.GetSpells().GetSpellBytes(); const auto allSpells = pugSpells | owynSpells; for (unsigned i = 0; i < 0x2d; i++) { //if (((1 << i) & allSpells) != 0) if (CheckBitSet(allSpells, i)) { pug.GetSpells().SetSpell(SpellIndex{i}); owyn.GetSpells().SetSpell(SpellIndex{i}); } } return ItemUseResult{ std::nullopt, // sound is in the dialog text not here item.GetItemIndex().mValue, DialogSources::mItemUseSucessful}; } ItemUseResult UsePotion( GameState& gameState, Character& character, InventoryIndex inventoryIndex) { auto& item = character.GetInventory().GetAtIndex(inventoryIndex); auto skill = ToSkill(BAK::SkillTypeMask{item.GetObject().mEffect}); auto adjust = item.GetObject().mPotionPowerOrBookChance; auto startTime = gameState.GetWorldTime().GetTime(); auto endTime = startTime + (Times::OneHour * item.GetObject().mAlternativeEffect); bool alreadyUsedThisPotionRecently{false}; for (const auto& affector : character.GetSkillAffectors()) { Logging::LogDebug(__FUNCTION__) << " TargetSkill: " << ToString(skill) << " Affector: " << affector << " time: " << startTime << "\n"; if (affector.mSkill == skill && affector.mEndTime >= startTime) { alreadyUsedThisPotionRecently = true; break; } } if (alreadyUsedThisPotionRecently) { return ItemUseResult{ std::nullopt, item.GetItemIndex().mValue, DialogSources::mCantConsumeMorePotion}; } character.AddSkillAffector(SkillAffector{0x200, skill, adjust, startTime, endTime}); auto result = ItemUseResult{ item.GetItemUseSound(), item.GetItemIndex().mValue, DialogSources::mItemUseSucessful}; character.GetInventory().RemoveItem(inventoryIndex, 1); return result; } ItemUseResult UseItem( GameState& gameState, Character& character, InventoryIndex inventoryIndex) { auto& item = character.GetInventory().GetAtIndex(inventoryIndex); auto& object = item.GetObject(); if (item.IsMagicUserOnly() && !character.IsSpellcaster()) { return ItemUseResult{ std::nullopt, item.GetItemIndex().mValue, BAK::DialogSources::mWarriorCantUseMagiciansItem}; } else if (item.IsSwordsmanUserOnly() && !character.IsSwordsman()) { return ItemUseResult{ std::nullopt, item.GetItemIndex().mValue, BAK::DialogSources::mMagicianCantUseWarriorsItem}; } if (object.mType == ItemType::Book) { return ReadBook(gameState, character, inventoryIndex); } else if (item.IsItemType(BAK::ItemType::Note)) { if (item.GetItemIndex() == sSpynote) { gameState.Apply( State::SetEventFlagTrue, State::sSpynoteHasBeenRead + item.GetQuantity()); return ItemUseResult{ std::nullopt, item.GetQuantity(), BAK::DialogSources::GetSpynote()}; } else { return ItemUseResult{ std::nullopt, item.GetItemIndex().mValue, DialogSources::mItemUseSucessful}; } } else if (item.IsItemType(BAK::ItemType::Scroll)) { return LearnSpell(character, inventoryIndex); } else if (item.GetItemIndex() == sPractiseLute) { return PractiseBarding(character, inventoryIndex); } else if (item.IsItemType(BAK::ItemType::ConditionModifier)) { return UseConditionModifier(character, inventoryIndex); } else if (item.IsItemType(BAK::ItemType::Restoratives)) { return UseRestoratives(character, inventoryIndex); } else if (item.IsItemType(BAK::ItemType::Potion)) { return UsePotion(gameState, character, inventoryIndex); } else if (item.IsItemType(BAK::ItemType::Light)) { return UseTorchOrRingOfPrandur(gameState, character, inventoryIndex); } else if (item.GetItemIndex() == sSilverthornAntiVenom) { return CurePoisoned(character, inventoryIndex); } else if (item.GetItemIndex() == sCupOfRlnnSkrr) { return UseCupOfRlnnSkrr(gameState, item); } return ItemUseResult{ std::nullopt, std::nullopt, KeyTarget{0}}; } }
23,175
C++
.cpp
671
27.321908
115
0.656636
xavieran/BaKGL
39
2
32
GPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,363
gameState.cpp
xavieran_BaKGL/bak/gameState.cpp
#include "bak/gameState.hpp" #include "bak/coordinates.hpp" #include "bak/dialogChoice.hpp" #include "bak/state/customStateChoice.hpp" #include "bak/state/dialog.hpp" #include "bak/state/event.hpp" #include "bak/state/encounter.hpp" #include "bak/state/lock.hpp" #include "bak/state/skill.hpp" #include "bak/state/temple.hpp" #include "bak/save.hpp" #include "bak/spells.hpp" #include "bak/state/dialog.hpp" #include "bak/dialogAction.hpp" #include "bak/time.hpp" #include <utility> namespace BAK { GameState::GameState() : GameState{nullptr} {} GameState::GameState( GameData* gameData) : mDialogCharacter{}, mActiveCharacter{CharIndex{0}}, mGameData{gameData}, mParty{ Royals{1000}, Inventory{20}, std::vector<Character>{ Character{ 0, "None", Skills{}, Spells{{}}, {}, {}, Conditions{}, Inventory{5}}}, std::vector<CharIndex>{CharIndex{0}}}, mContextValue_7530{0}, mShopType_7542{0}, mItemValue_753e{0}, mSkillValue{0}, mSelectedItem{}, mCurrentMonster{}, mChapter{1}, mZone{1}, mEndOfDialogState{0}, mContainers{}, mGDSContainers{}, mCombatContainers{}, mTextVariableStore{}, mFullMap{}, mLogger{Logging::LogState::GetLogger("GameState")} { if (mGameData != nullptr) { LoadGameData(mGameData); } } void GameState::LoadGameData(GameData* gameData) { ASSERT(gameData); mGameData = gameData; mGDSContainers.clear(); mCombatContainers.clear(); mContainers.clear(); for (unsigned i = 0; i < 13; i++) { mContainers.emplace_back(mGameData->LoadContainers(i)); } mGDSContainers = mGameData->LoadShops(); mCombatContainers = mGameData->LoadCombatInventories(); mTimeExpiringState = mGameData->LoadTimeExpiringState(); mSpellState = mGameData->LoadSpells(); mZone = ZoneNumber{mGameData->mLocation.mZone}; mChapter = mGameData->mChapter; } const Party& GameState::GetParty() const { if (mGameData) { return mGameData->mParty; } return mParty; } Party& GameState::GetParty() { if (mGameData) { return mGameData->mParty; } return mParty; } std::int16_t GameState::GetEndOfDialogState() const { return mEndOfDialogState; } void GameState::DoSetEndOfDialogState(std::int16_t state) { mEndOfDialogState = state; } void GameState::SetActiveCharacter(ActiveCharIndex character) { mActiveCharacter = GetParty().GetCharacter(character).mCharacterIndex; mTextVariableStore.SetActiveCharacter( GetParty().GetCharacter(character).mName); } void GameState::SetActiveCharacter(CharIndex character) { mActiveCharacter = character; mTextVariableStore.SetActiveCharacter( GetParty().GetCharacter(character).mName); } const TextVariableStore& GameState::GetTextVariableStore() const { return mTextVariableStore; } TextVariableStore& GameState::GetTextVariableStore() { return mTextVariableStore; } void GameState::SetChapter(Chapter chapter) { mChapter = chapter; } Chapter GameState::GetChapter() const { return mChapter; } void GameState::SetMonster(MonsterIndex monster) { mCurrentMonster = monster; } Royals GameState::GetMoney() const { if (mGameData) return GetParty().GetGold(); return Royals{1000}; } void GameState::SetLocation(Location loc) { mLogger.Debug() << "SetLocation to: " << loc << "\n"; mZone = ZoneNumber{loc.mZone}; if (mGameData) { mGameData->mLocation = loc; } } void GameState::SetLocation(GamePositionAndHeading posAndHeading) { if (mGameData) { const auto loc = Location{ mZone, GetTile(posAndHeading.mPosition), posAndHeading}; mGameData->mLocation = loc; } } void GameState::SetMapLocation(MapLocation location) const { mLogger.Info() << "Setting map location to: " << location << " from : " << mGameData->mMapLocation << "\n"; if (mGameData) mGameData->mMapLocation = location; } GamePositionAndHeading GameState::GetLocation() const { if (mGameData) return mGameData->mLocation.mLocation; return GamePositionAndHeading{glm::uvec2{10 * 64000, 15 * 64000}, 0 }; } MapLocation GameState::GetMapLocation() const { if (mGameData) return mGameData->mMapLocation; return MapLocation{{20, 20}, 0}; } ZoneNumber GameState::GetZone() const { return mZone; } const WorldClock& GameState::GetWorldTime() const { if (mGameData) { return mGameData->mTime; } else { return mFakeWorldClock; } } WorldClock& GameState::GetWorldTime() { if (mGameData) { return mGameData->mTime; } else { return mFakeWorldClock; } } void GameState::SetTransitionChapter_7541(bool value) { mTransitionChapter_7541 = value; } bool GameState::GetTransitionChapter_7541() const { return mTransitionChapter_7541; } void GameState::SetShopType_7542(unsigned shopType) { mShopType_7542 = shopType; } unsigned GameState::GetShopType_7542() const { return mShopType_7542; } GenericContainer* GameState::GetContainerForGDSScene(HotspotRef ref) { for (auto& shop : mGDSContainers) { if (shop.GetHeader().GetHotspotRef() == ref) return &shop; } return nullptr; } GenericContainer* GameState::GetWorldContainer(ZoneNumber zone, GamePosition location) { for (auto& container : GetContainers(zone)) { if (container.GetHeader().GetPosition() == location) { return &container; } } return nullptr; } GenericContainer const* GameState::GetWorldContainer(ZoneNumber zone, GamePosition location) const { for (auto& container : GetContainers(zone)) { if (container.GetHeader().GetPosition() == location) { return &container; } } return nullptr; } std::optional<unsigned> GameState::GetActor(unsigned actor) const { if (actor == 0xff) { if (!mDialogCharacter) { const auto& character = GetParty().GetCharacter(ActiveCharIndex{0}); return character.mCharacterIndex.mValue + 1; } else { const auto& character = GetParty().GetCharacter(*mDialogCharacter); return character.mCharacterIndex.mValue + 1; } } else if (actor == 0xfe) { return GetPartyLeader().mValue + 1; } else if (actor == 0xfd) { // Use party follower index? // this logicc is not quite right return mDialogCharacterList[5] + 1; } else if (actor >= 0xf0) { //0xf0 - use the character list for diags to pick a character? assert(mDialogCharacterList[actor - 0xf0] != 0xff); return mDialogCharacterList[actor - 0xf0] + 1; } else if (actor == 0xc8) { return std::nullopt; } else { return actor; } } bool GameState::GetSpellActive(StaticSpells spell) const { return mSpellState.SpellActive(spell); } // prefer to use this function when getting best skill // as it will set the appropriate internal state. std::pair<CharIndex, unsigned> GameState::GetPartySkill(SkillType skill, bool best) { const auto [character, value] = GetParty().GetSkill(skill, best); mSkillCheckedCharacter = character; mSkillValue = value; return std::make_pair(character, value); } void GameState::SetCharacterTextVariables() { DoSetEndOfDialogState(0); if (GetParty().GetNumCharacters() > 0) { SetDefaultDialogTextVariables(); } } void GameState::SetDefaultDialogTextVariables() { for (auto& c : mDialogCharacterList) { c = 0xff; } // index 4 gets party leader SetDialogTextVariable(4, 7); // Select random characters for indices 5, 3, and 0 SetDialogTextVariable(5, 0xF); SetDialogTextVariable(3, 0xE); SetDialogTextVariable(0, 0x1f); } void GameState::SetDialogTextVariable(unsigned index, unsigned attribute) { mLogger.Spam() << __FUNCTION__ << "(" << index << ", " << attribute << ")\n"; assert(attribute > 0); // remember we always switch on attribute - 1... switch (attribute - 1) { case 0: [[fallthrough]]; case 1: [[fallthrough]]; case 2: [[fallthrough]]; case 3: [[fallthrough]]; case 4: [[fallthrough]]; case 5: mDialogCharacterList[index] = attribute - 1; mTextVariableStore.SetTextVariable(index, GetParty().GetCharacter(CharIndex{attribute - 1}).GetName()); break; case 6: mDialogCharacterList[index] = GetPartyLeader().mValue; mTextVariableStore.SetTextVariable(index, GetParty().GetCharacter(GetPartyLeader()).GetName()); break; case 10: mDialogCharacterList[index] = mActiveCharacter.mValue; mTextVariableStore.SetTextVariable(index, GetParty().GetCharacter(mActiveCharacter).GetName()); break; case 11: mDialogCharacterList[index] = mSkillCheckedCharacter.mValue; mTextVariableStore.SetTextVariable(index, GetParty().GetCharacter(mSkillCheckedCharacter).GetName()); break; case 12: [[fallthrough]]; case 13: [[fallthrough]]; case 14: [[fallthrough]]; case 15: [[fallthrough]]; case 30: SelectRandomActiveCharacter(index, attribute); break; case 7: [[fallthrough]]; case 8: [[fallthrough]]; case 23: [[fallthrough]]; case 24: [[fallthrough]]; case 25: break; // Do nothing..? case 16: mTextVariableStore.SetTextVariable( index, mCurrentMonster ? MonsterNames::Get().GetMonsterName(*mCurrentMonster) : "No Monster Specified"); break; case 17: ASSERT(mSelectedItem); mTextVariableStore.SetTextVariable( index, mSelectedItem->GetObject().mName); break; case 18: mTextVariableStore.SetTextVariable( index, ToShopDialogString(mItemValue_753e)); break; case 19: mTextVariableStore.SetTextVariable( index, ToShopDialogString(GetParty().GetGold())); break; case 20: // mContextVar_valueOfItem - but used // in the restoratives dialog to indicate the // number of health points left... mTextVariableStore.SetTextVariable( index, ""); // ToString(mContextVar_charCurrentHealthPoint) break; case 21: mTextVariableStore.SetTextVariable( index, ""); // ToString(mContextVar_753f) case 22: // unused?? // ToString(mContext_whichSkillIncreased) break; case 26: // mTextVariableStore.SetTextVariable(index, // ToString(SkillType(mContextVar_753f))); break; case 27: // or tavernkeeper if in an inn... which is determined by // inn cost being >= 0 mTextVariableStore.SetTextVariable(index, "shopkeeper"); break; case 28: // the skill that increased, either the party's or the // selected character // mContext_whichSkillIncreased mTextVariableStore.SetTextVariable(index, "skill"); break; case 9: case 29: // character index is stored in checkSkillValue //mDialogCharacterList[index] =checkedSkillValue; mTextVariableStore.SetTextVariable( index, ""); // character at checked skill value break; case 31: // actor name break; default: break; } mLogger.Debug() << __FUNCTION__ << " chose: " << +mDialogCharacterList[index] << "\n"; } CharIndex GameState::GetPartyLeader() const { static constexpr std::array<CharIndex, 9> partyLeaderPerChapter = {Locklear, James, James, Gorath, James, Owyn, James, Owyn, Pug}; if (GetParty().FindActiveCharacter(Pug)) { return Pug; } else { return partyLeaderPerChapter[GetChapter().mValue - 1]; } } void GameState::SelectRandomActiveCharacter(unsigned index, unsigned attribute) { mLogger.Debug() << __FUNCTION__ << "(" << index << ", " << attribute << ")\n"; bool foundValidCharacter = false; unsigned limit = 0x1f8; // is this right...? or is it the opposite of the party leader that we should choose by default? auto chosenChar = GetPartyLeader(); auto CharacterAlreadyExists = [&](auto character){ for (unsigned i = 0; i < index; i++) { if (mDialogCharacterList[i] == character.mValue) return true; } return false; }; while (!foundValidCharacter && limit != 0) { limit--; auto randomChar = ActiveCharIndex{GetRandomNumber(0, GetParty().GetNumCharacters() - 1)}; chosenChar = GetParty().GetCharacter(randomChar).mCharacterIndex; if (CharacterAlreadyExists(chosenChar)) { continue; } switch (attribute) { case 14: // Magicians if (chosenChar == Owyn || chosenChar == Pug || chosenChar == Patrus) { foundValidCharacter = true; } break; case 15: // Swordsmen if (chosenChar == Locklear || chosenChar == Gorath || chosenChar == James) { foundValidCharacter = true; } break; case 16: // Third-ary character? if (chosenChar == Gorath || chosenChar == Patrus) { foundValidCharacter = true; } break; case 31: if (chosenChar != GetPartyLeader()) { foundValidCharacter = true; } break; default: foundValidCharacter = true; break; } } mTextVariableStore.SetTextVariable(index, GetParty().GetCharacter(chosenChar).GetName()); mDialogCharacterList[index] = chosenChar.mValue; } void GameState::EvaluateAction(const DialogAction& action) { std::visit(overloaded{ [&](const SetFlag& set) { mLogger.Debug() << "Setting flag of event: " << DialogAction{set} << "\n"; SetEventState(set); }, [&](const SetTextVariable& set) { mLogger.Debug() << "Setting text variable: " << DialogAction{set} << "\n"; SetDialogTextVariable(set.mWhich, set.mWhat); }, [&](const LoseItem& lose) { mLogger.Debug() << "Losing item: " << lose << "\n"; auto& party = GetParty(); party.RemoveItem(lose.mItemIndex, lose.mQuantity); }, [&](const GiveItem& give) { mLogger.Debug() << "Giving item: " << give << "\n"; if (give.mWho <= 1) { auto& party = GetParty(); party.GainItem(give.mItemIndex, give.mQuantity); } else { auto characterToGive = mDialogCharacterList[give.mWho - 2]; GetParty().GetCharacter(CharIndex{characterToGive}).GiveItem( InventoryItemFactory::MakeItem(ItemIndex{give.mItemIndex}, give.mQuantity)); } }, [&](const GainSkill& skill) { auto amount = skill.mMax; if (skill.mMin != skill.mMax) { amount = skill.mMin + (GetRandomNumber(0, 0xfff) % (skill.mMax - skill.mMin)); } if (skill.mWho <= 1) { mLogger.Debug() << "Gaining skill: " << skill << " - with amount: " << amount << " for all chars\n"; GetParty().ImproveSkillForAll( skill.mSkill, SkillChange::Direct, amount); } // there are two character index arrays in the code, starting at 0x4df0 and 0x4df2 // The dala one specifically uses query choice dialog to select the character, and // places this in 4df2[0], i.e. 4df0[2], so the skill.mWho is effecting -= 2 // Since skill.mWho <= 1 doesn't use the array anyway, we always use the array // that starts at 0x4df2 else { mLogger.Debug() << "Gaining skill: " << skill << " - with amount: " << amount << " for " << +mDialogCharacterList[skill.mWho - 2] << "\n"; auto characterToImproveSkill = mDialogCharacterList[skill.mWho - 2]; GetParty().GetCharacter(CharIndex{characterToImproveSkill}) .ImproveSkill(skill.mSkill, SkillChange::Direct, amount); } }, [&](const HealCharacters& heal) { if (heal.mWho <= 1) { mLogger.Debug() << "Healing party by: " << heal.mHowMuch << "\n"; GetParty().ForEachActiveCharacter([&](auto& character){ HealCharacter(character.mCharacterIndex, heal.mHowMuch); return Loop::Continue; }); } else { auto character = mDialogCharacterList[heal.mWho - 2]; mLogger.Debug() << "Healing character by amount: " << heal.mHowMuch << " for " << +character << "\n"; HealCharacter(CharIndex{character}, heal.mHowMuch); } }, [&](const SpecialAction& action) { EvaluateSpecialAction(action); }, [&](const GainCondition& cond) { auto amount = cond.mMax; if (cond.mMin != cond.mMax) { amount = cond.mMin + (GetRandomNumber(0, 0xfff) % (cond.mMax - cond.mMin)); } if (cond.mWho > 1) { auto characterToAffect = CharIndex{mDialogCharacterList[cond.mWho - 2]}; mLogger.Debug() << "Gaining condition : " << cond << " - with amount: " << amount << " for " << characterToAffect << "\n"; GetParty().GetCharacter(characterToAffect).GetConditions() .IncreaseCondition(cond.mCondition, amount); } else { mLogger.Debug() << "Gaining condition : " << cond << " - with amount: " << amount << " for all\n"; GetParty().ForEachActiveCharacter( [&](auto& character){ character.GetConditions().IncreaseCondition( cond.mCondition, amount); return Loop::Continue; }); } }, [&](const SetAddResetState& state) { mLogger.Debug() << "Setting time expiring state: " << state << "\n"; SetEventValue(state.mEventPtr, 1); AddTimeExpiringState(mTimeExpiringState, ExpiringStateType::ResetState, state.mEventPtr, 0x40, state.mTimeToExpire); }, [&](const ElapseTime& elapse) { mLogger.Debug() << "Elapsing time: " << elapse << "\n"; DoElapseTime(elapse.mTime); }, [&](const SetTimeExpiringState& state) { mLogger.Debug() << "Setting time expiring state2: " << state << "\n"; AddTimeExpiringState( mTimeExpiringState, state.mType, state.mEventPtr, state.mFlags, state.mTimeToExpire); }, [&](const SetEndOfDialogState& state) { mLogger.Debug() << "Setting end of dialog state: " << state << "\n"; DoSetEndOfDialogState(state.mState); }, [&](const UpdateCharacters& update) { GetParty().SetActiveCharacters(update.mCharacters); }, [&](const LoadSkillValue& load) { mLogger.Debug() << "Loading skill value: " << load << "\n"; GetPartySkill(load.mSkill, load.mTarget == 1); }, [&](const LearnSpell& learnSpell) { mLogger.Debug() << "Learning Spell: " << learnSpell << "\n"; GetParty().GetCharacter(CharIndex{mDialogCharacterList[learnSpell.mWho]}) .GetSpells().SetSpell(learnSpell.mWhichSpell); }, [&](const LoseNOfItem& loss) { for (unsigned i = 0; i < loss.mQuantity; i++) { GetParty().RemoveItem(loss.mItemIndex, 1); } }, [&](const auto& a){ mLogger.Debug() << "Doing nothing for: " << a << "\n"; }}, action); } void GameState::EvaluateSpecialAction(const SpecialAction& action) { mLogger.Debug() << "Evaluating special action: " << action << "\n"; using enum SpecialActionType; switch (action.mType) { case ReduceGold: GetParty().LoseMoney(mItemValue_753e); break; case IncreaseGold: GetParty().GainMoney(mItemValue_753e); break; case RepairAllEquippedArmor: mLogger.Debug() << "Reparing party armor\n"; GetParty().ForEachActiveCharacter([&](auto& character) { auto armor = character.GetInventory().FindEquipped(ItemType::Armor); if (armor != character.GetInventory().GetItems().end()) { armor->SetCondition(100); armor->SetRepairable(false); } return Loop::Continue; }); break; // I don't think this is used anywhere case CopyStandardInnToShop0: [[fallthrough]]; case CopyStandardInnToShop1: { auto* refInn1 = GetWorldContainer(ZoneNumber{0}, {20, 0}); assert(refInn1); auto* inn1 = GetContainerForGDSScene(HotspotRef{2, 'C'}); assert(inn1); inn1->GetInventory().GetItems().clear(); inn1->GetInventory().CopyFrom(refInn1->GetInventory()); } break; case Increase753f: mLogger.Debug() << "Increasing dialog var 753f from: " << mContextVar_753f << " to: " << (mContextVar_753f + action.mVar1) << "\n"; mContextVar_753f += action.mVar1; break; case Gamble: DoGamble(action.mVar1, action.mVar2, action.mVar3); break; case ReturnAlcoholToShops: { auto* refInn1 = GetWorldContainer(ZoneNumber{0}, {20, 0}); assert(refInn1); auto* inn1 = GetContainerForGDSScene(HotspotRef{60, 'C'}); assert(inn1); inn1->GetInventory().GetItems().clear(); inn1->GetInventory().CopyFrom(refInn1->GetInventory()); auto* refInn2 = GetWorldContainer(ZoneNumber{0}, {30, 0}); assert(refInn2); auto* inn2 = GetContainerForGDSScene(HotspotRef{64, 'C'}); assert(inn2); inn2->GetInventory().GetItems().clear(); inn2->GetInventory().CopyFrom(refInn2->GetInventory()); } break; case ResetGambleValueTo: mBardReward_754d = action.mVar1; break; case RepairAndBlessEquippedSwords: GetParty().ForEachActiveCharacter([&](auto& character) { auto sword = character.GetInventory().FindEquipped(ItemType::Sword); if (sword != character.GetInventory().GetItems().end()) { sword->SetCondition(100); sword->SetRepairable(false); sword->SetModifier(Modifier::Blessing3); } return Loop::Continue; }); break; case ExtinguishAllLightSources: { for (auto& state : mTimeExpiringState) { if (state.mType == ExpiringStateType::Light && state.mData == 0) { state.mDuration = Time{0}; } } ReduceAndEvaluateTimeExpiringState(Time{0}); } break; case EmptyArlieContainer: { auto* container = GetWorldContainer(ZoneNumber{3}, GamePosition{1308000, 1002400}); assert(container); container->GetInventory().GetItems().clear(); } break; case UnifyOwynAndPugsSpells: { auto& pug = GetParty().GetCharacter(Pug); auto& owyn = GetParty().GetCharacter(Owyn); const auto pugSpells = pug.GetSpells().GetSpellBytes(); const auto owynSpells = owyn.GetSpells().GetSpellBytes(); const auto allSpells = pugSpells | owynSpells; for (unsigned i = 0; i < 0x2d; i++) { if (CheckBitSet(allSpells, i)) { pug.GetSpells().SetSpell(SpellIndex{i}); owyn.GetSpells().SetSpell(SpellIndex{i}); } } } break; default: mLogger.Debug() << "Unhandled action:" << action << "\n"; } } void GameState::DoGamble(unsigned playerChance, unsigned gamblerChance, unsigned reward) { mContextVar_753f = GetRandomNumber(0, 0xfff) % playerChance; mShopType_7542 = GetRandomNumber(0, 0xfff) % gamblerChance; mLogger.Debug() << "Rolled for player: " << mContextVar_753f << " for gambler: " << mShopType_7542 << "\n"; if (mContextVar_753f <= mShopType_7542) { mLogger.Debug() << "Gambler won\n"; if (mContextVar_753f >= mShopType_7542) { mLogger.Debug() << "Drew with gambler\n"; if (mContextVar_753f == mShopType_7542) { SetDialogContext_7530(2); } } else { mLogger.Debug() << "We lost " << mItemValue_753e << "\n"; SetDialogContext_7530(1); GetParty().LoseMoney(mItemValue_753e); if (mBardReward_754d <= 60000) { mBardReward_754d += mItemValue_753e.mValue; } } } else { mLogger.Debug() << "We won " << mItemValue_753e << "\n"; SetDialogContext_7530(0); const auto winnings = Royals{(mItemValue_753e.mValue * reward) / 100}; GetParty().GainMoney(winnings); mBardReward_754d = (winnings.mValue > mBardReward_754d) ? 0 : (mBardReward_754d - winnings.mValue); //auto& character = GetParty().GetCharacter(mSelectedCharacter); } } unsigned GameState::GetGameState(const GameStateChoice& choice) const { switch (choice.mState) { case ActiveStateFlag::Chapter: return GetChapter().mValue; case ActiveStateFlag::Context: return mContextValue_7530; case ActiveStateFlag::CantAfford: return static_cast<unsigned>(GetMoney() > mItemValue_753e); case ActiveStateFlag::SkillCheck: return mSkillValue; case ActiveStateFlag::Money: return Sovereigns{GetMoney().mValue}.mValue;; case ActiveStateFlag::TimeBetween: return GetWorldTime().GetTime().GetHour(); case ActiveStateFlag::NightTime: { const auto time = GetWorldTime().GetTime(); const auto hour = time.GetHour(); const unsigned result = hour < 4 || hour >= 20; mLogger.Debug() << "Checking NightTime choice: " << time << " hr: " << hour << " -- " << result << "\n"; return result; } case ActiveStateFlag::DayTime: { const auto time = GetWorldTime().GetTime(); const auto hour = time.GetHour(); const unsigned result = hour >= 4 && hour < 20; mLogger.Debug() << "Checking DayTime choice: " << time << " hr: " << hour << " -- " << result << "\n"; return result; } case ActiveStateFlag::Shop: return GetShopType_7542(); case ActiveStateFlag::Context_753f: return mContextVar_753f; case ActiveStateFlag::Gambler: return static_cast<unsigned>(mBardReward_754d); case ActiveStateFlag::ItemValue_753e: return mItemValue_753e.mValue; default: return 0u; } } bool GameState::EvaluateDialogChoice(const DialogChoice& choice) const { if (std::holds_alternative<NoChoice>(choice.mChoice)) { return true; } else if (!std::holds_alternative<ComplexEventChoice>(choice.mChoice)) { const unsigned state = GetEventState(choice.mChoice); auto result = state >= choice.mMin && ((choice.mMax == 0xffff) || (state <= choice.mMax)); mLogger.Info() << "Evaluating choice: "<< choice << " state is: " << state << "result: " << result << "\n"; return result; } else { const auto& complexChoice = std::get<ComplexEventChoice>(choice.mChoice); const unsigned state = ReadEvent(complexChoice.mEventPointer); // Probably want to put this logic somewhere else... // if eventPtr % 10 != 0 const auto [byteOffset, bitOffset] = State::CalculateComplexEventOffset(complexChoice.mEventPointer); mLogger.Debug() << __FUNCTION__ << " : " << choice << " S: [" << std::hex << +state << std::dec << "] - byteOff: " << + byteOffset << " bitOff: " << +bitOffset << "\n"; const auto xorMask = static_cast<std::uint8_t>(choice.mMin & 0xff); const auto expected = static_cast<std::uint8_t>(choice.mMin >> 8); const auto mustEqualExpected = static_cast<std::uint8_t>(choice.mMax& 0xff); const auto chapterMask = static_cast<std::uint8_t>(choice.mMax >> 8); //static_cast<std::uint8_t>(choice1 & 0xff), //static_cast<std::uint8_t>(choice1 >> 8) if (mGameData && bitOffset != 0) { return (state >= xorMask) && (state <= mustEqualExpected); } // Need to double check this... //const auto chapterFlag = GetChapter() == Chapter{9} // ? 0x80 // : 1 << (GetChapter().mValue - 1); //const auto chapterMaskSatisfied = (chapterFlag & ChapterMask) == 0; const auto chapterMaskSatisfied = true; if (mustEqualExpected) { if (((state ^ xorMask) & expected) == expected && chapterMaskSatisfied) { return true; } else { return false; } } else { if (((state ^ xorMask) & expected) != 0 && chapterMaskSatisfied) { return true; } else { return false; } } } } unsigned GameState::GetEventState(Choice choice) const { return std::visit(overloaded{ [&](const NoChoice& c) -> unsigned { return true; }, [&](const EventFlagChoice& c) -> unsigned { return ReadEventBool(c.mEventPointer); }, [&](const ComplexEventChoice& c) -> unsigned { return ReadEventBool(c.mEventPointer); }, [&](const InventoryChoice& c) -> unsigned { return GetParty().HaveItem(c.mRequiredItem); }, [&](const GameStateChoice& c) -> unsigned { return GetGameState(c); }, [&](const CastSpellChoice& c) -> unsigned { return GetSpellActive(static_cast<StaticSpells>(c.mRequiredSpell)); }, [&](const HaveNoteChoice& c) -> unsigned { return HaveNote(c.mRequiredNote); }, [&](const CustomStateChoice& c) -> unsigned { const auto stateChecker = State::CustomStateEvaluator{*this}; switch (c.mScenario) { case Scenario::MortificationOfTheFlesh: return stateChecker.AnyCharacterStarving(); case Scenario::Plagued: return stateChecker.Plagued(); case Scenario::HaveSixSuitsOfArmor: return stateChecker.HaveSixSuitsOfArmor(); case Scenario::AllPartyArmorIsGoodCondition: return stateChecker.AllPartyArmorIsGoodCondition(); case Scenario::PoisonedDelekhanArmyChests: return stateChecker.PoisonedDelekhanArmyChests(); case Scenario::AnyCharacterSansWeapon: return stateChecker.AnyCharacterSansWeapon(); case Scenario::AlwaysFalse: [[fallthrough]]; case Scenario::AlwaysFalse2: return false; case Scenario::AnyCharacterHasNegativeCondition: return stateChecker.AnyCharacterHasNegativeCondition(); case Scenario::AllPartyMembersHaveNapthaMask: return stateChecker.AllCharactersHaveNapthaMask(); case Scenario::NormalFoodInArlieChest: return stateChecker.NormalFoodInArlieChest(); case Scenario::PoisonedFoodInArlieChest: return stateChecker.PoisonedFoodInArlieChest(); default: return false; } }, [&](const RandomChoice& c){ return GetRandomNumber(0, 0xfff) % c.mRange; }, [&](const auto& c) -> unsigned { return false; } }, choice); } unsigned GameState::ReadEvent(unsigned eventPtr) const { if (eventPtr == std::to_underlying(ActiveStateFlag::DayTime)) { return GetGameState(GameStateChoice{ActiveStateFlag::DayTime}); } if (mGameData != nullptr) { return State::ReadEvent(mGameData->GetFileBuffer(), eventPtr); } else return 0; } bool GameState::ReadEventBool(unsigned eventPtr) const { return (ReadEvent(eventPtr) & 0x1) == 1; } void GameState::SetEventValue(unsigned eventPtr, unsigned value) { if (eventPtr == 0x7541) { mTransitionChapter_7541 = value; return; } if (mGameData) State::SetEventFlag(mGameData->GetFileBuffer(), eventPtr, value); } void GameState::SetEventState(const SetFlag& setFlag) { if (setFlag.mEventPointer == 0x753e) { mItemValue_753e = Royals{setFlag.mEventValue}; } else if (setFlag.mEventPointer == 0x753f) { mContextVar_753f = setFlag.mEventValue; } else if (setFlag.mEventPointer == 0x7541) { mTransitionChapter_7541 = setFlag.mEventValue; } else if (mGameData) { State::SetEventDialogAction(mGameData->GetFileBuffer(), setFlag); } } bool GameState::GetMoreThanOneTempleSeen() const { if (mGameData) { unsigned templesSeen = 0; for (unsigned i = 1; i < 13; i++) { templesSeen += State::ReadTempleSeen(*this, i); } return templesSeen > 1; } return true; } void GameState::SetDialogContext_7530(unsigned contextValue) { mContextValue_7530 = contextValue; } void GameState::SetItemValue(Royals value) { mItemValue_753e = value; } void GameState::SetBardReward_754d(unsigned value) { mBardReward_754d = value; } unsigned GameState::GetBardReward_754d() { return mBardReward_754d; } void GameState::SetInventoryItem(const InventoryItem& item) { mSelectedItem = item; } void GameState::ClearUnseenImprovements(unsigned character) { if (mGameData) { State::ClearUnseenImprovements(mGameData->GetFileBuffer(), character); } } bool GameState::SaveState() { if (mGameData) { BAK::Save(GetWorldTime(), mGameData->GetFileBuffer()); BAK::Save(GetParty(), mGameData->GetFileBuffer()); for (const auto& container : mGDSContainers) BAK::Save(container, mGameData->GetFileBuffer()); for (const auto& container : mCombatContainers) BAK::Save(container, mGameData->GetFileBuffer()); for (const auto& zoneContainers : mContainers) for (const auto& container : zoneContainers) BAK::Save(container, mGameData->GetFileBuffer()); BAK::Save(mTimeExpiringState, mGameData->GetFileBuffer()); BAK::Save(mSpellState, mGameData->GetFileBuffer()); BAK::Save(mChapter, mGameData->GetFileBuffer()); auto mapLocation = MapLocation{ mFullMap.GetTileCoords(mZone, GetTile(GetLocation().mPosition)), HeadingToFullMapAngle(GetLocation().mHeading) }; BAK::Save(mapLocation, mGameData->GetFileBuffer()); BAK::Save(mGameData->mLocation, mGameData->GetFileBuffer()); return true; } return false; } bool GameState::Save(const SaveFile& saveFile) { if (SaveState()) { mGameData->Save(saveFile); return true; } return false; } bool GameState::Save(const std::string& saveName) { if (SaveState()) { mGameData->Save(saveName, saveName); return true; } return false; } std::vector<GenericContainer>& GameState::GetContainers(ZoneNumber zone) { ASSERT(zone.mValue < 13); return mContainers[zone.mValue]; } const std::vector<GenericContainer>& GameState::GetContainers(ZoneNumber zone) const { ASSERT(zone.mValue < 13); return mContainers[zone.mValue]; } bool GameState::HaveNote(unsigned note) const { bool haveNote = false; GetParty().ForEachActiveCharacter( [&](const auto& character){ const auto& items = character.GetInventory().GetItems(); for (const auto& item : items) { if (item.IsItemType(ItemType::Note) && item.GetCondition() == note) { haveNote = true; return Loop::Finish; } } return Loop::Continue; }); return haveNote; } bool GameState::CheckConversationItemAvailable(unsigned conversationItem) const { const auto stateChecker = State::CustomStateEvaluator{*this}; const bool enabled = ReadEventBool(conversationItem); const bool available = std::invoke([&](){ switch (conversationItem) { case 9: if (!enabled) return false; return !GetParty().HaveItem(sWaani); case 11: if (!enabled) return false; return !GetParty().HaveItem(sBagOfGrain); case 133: return GetEventState(CreateChoice(0xdb94)) != 0; case 130: return GetEventState(CreateChoice(0xdb9e)) != 0; case 44: if (!enabled) return false; return ReadEventBool(0x1f6c); case 117: if (!enabled) return false; return GetChapter() == Chapter{6}; case 17: [[fallthrough]]; case 103: if (!enabled) return false; return stateChecker.AnyCharacterHasNegativeCondition(); case 71: if (!enabled) return false; return false; // (owynsSpells & 0x10) != 0; (Have spell 20 (Unfortunate flux)) case 132: if (!enabled) return false; return HaveNote(0x15) || ReadEventBool(0x1979); case 106: if (!enabled) return false; return true; // owynsOtherSpells & 0x200 case 164: if (!enabled) return false; return ReadEventBool(0x1972); case 76: [[fallthrough]]; case 148: if (!enabled) return false; return !GetParty().HaveItem(sRations); case 163: return ReadEventBool(0x8e) && ReadEventBool(0xaa) && GetParty().HaveItem(sAbbotsJournal); default: return enabled; } }); return available && !State::CheckConversationOptionInhibited(*this, conversationItem); } void GameState::DoElapseTime(Time time) { // need to accumulate these and commit when the // dialog is over..? auto splitTime = time; auto camp = TimeChanger{*this}; bool dialogResetsSleep = time > Times::TwelveHours; // there is further logic to this that determines // whether we consume rations or not. // e.g. cutter's gap in highcastle consumes rations, // zone transitions do not... bool dialogConsumesRations = true; while (splitTime > Times::OneHour) { if (dialogResetsSleep) { GetWorldTime().SetTimeLastSlept( GetWorldTime().GetTime()); } splitTime = splitTime - Times::OneHour; camp.HandleGameTimeChange( Times::OneHour, true, dialogConsumesRations, false, 0, 0); } if (splitTime > Time{0}) { camp.HandleGameTimeChange( splitTime, true, dialogConsumesRations, false, 0, 0); } } void GameState::ReduceAndEvaluateTimeExpiringState(Time delta) { for (unsigned i = 0; i < mTimeExpiringState.size(); i++) { auto& state = mTimeExpiringState[i]; if (state.mDuration < delta) { state.mDuration = Time{0}; } else { state.mDuration -= delta; } if (state.mType == ExpiringStateType::Light) { RecalculatePalettesForPotionOrSpellEffect(state); } else if (state.mType == ExpiringStateType::Spell) { SetSpellState(state); } else if (state.mDuration == Time{0}) { if (state.mType == ExpiringStateType::SetState) { SetEventValue(state.mData, 1); } else if (state.mType == ExpiringStateType::ResetState) { SetEventValue(state.mData, 0); } } } std::erase_if( mTimeExpiringState, [](auto& state){ return state.mDuration == Time{0}; }); } void GameState::RecalculatePalettesForPotionOrSpellEffect(TimeExpiringState& state) { auto time = state.mDuration.mTime / 0x1e; switch (state.mData) { case 0: // torch or ring of prandur { if (time >= 8) { // paletteModifier1 = 0x31; } else { //paletteModifier1 = time * time; } if (state.mDuration == Time{0}) { DeactivateLightSource(); } } break; case 1: // dragon's breath { } break; case 2: // candle glow { } break; case 3: // stardusk { } break; } } void GameState::DeactivateLightSource() { mLogger.Debug() << "Deactivating light source\n"; GetParty().ForEachActiveCharacter([&](auto& character) { auto& items = character.GetInventory().GetItems(); for (unsigned i = 0; i < items.size(); i++) { auto& item = items[i]; if (item.IsActivated() && (item.GetItemIndex() == sTorch || item.GetItemIndex() == sRingOfPrandur)) { item.SetQuantity(item.GetQuantity() - 1); item.SetActivated(false); if (item.GetQuantity() == 0 && item.GetItemIndex() == sTorch) { character.GetInventory().RemoveItem(InventoryIndex{i}); } return Loop::Finish; } } return Loop::Continue; }); } bool GameState::HaveActiveLightSource() { for (auto& state : mTimeExpiringState) { if (state.mType == ExpiringStateType::Light && state.mData == 0) { return true; } } return false; } void GameState::SetSpellState(const TimeExpiringState& state) { if (state.mData > 9) { assert(false); return; } if (state.mDuration == Time{0}) { mSpellState.SetSpellState(StaticSpells{state.mData}, false); } else { mSpellState.SetSpellState(StaticSpells{state.mData}, true); } } void GameState::CastStaticSpell(StaticSpells spell, Time duration) { mLogger.Debug() << "Casting spell: " << spell << " for: " << duration << "\n"; // RunDialog DialogSources::GetSpellCastDialog(static_cast<unsigned>(spell)); auto* state = AddSpellTimeExpiringState(mTimeExpiringState, static_cast<unsigned>(spell), duration); assert(state); SetSpellState(*state); switch (spell) { case StaticSpells::DragonsBreath: [[fallthrough]]; case StaticSpells::CandleGlow: [[fallthrough]]; case StaticSpells::Stardusk: { auto* lightState = AddLightTimeExpiringState( mTimeExpiringState, static_cast<unsigned>(spell) + 1, duration); assert(lightState); RecalculatePalettesForPotionOrSpellEffect(*lightState); // UpdatePaletteIfRequired() } break; default: break; } mLogger.Debug() << "State now: " << mTimeExpiringState << "\n"; mLogger.Debug() << "SpellState now: " << std::hex << mSpellState.GetSpells() << std::dec << "\n"; // HandlePostSpellcastingReduceHealth } bool GameState::CanCastSpell(SpellIndex spell, ActiveCharIndex activeChar) { const auto& character = GetParty().GetCharacter(activeChar); // FIXME: Add additional conditions, e.g. Stardusk only works outdoors... const auto& spellInfo = SpellDatabase::Get().GetSpell(spell); if (character.GetSkill(SkillType::TotalHealth) < spellInfo.mMinCost) return false; return character.GetSpells().HaveSpell(spell); } void GameState::HealCharacter(CharIndex who, unsigned amount) { auto& character = GetParty().GetCharacter(who); if (amount >= 0x64) { GetWorldTime().SetTimeLastSlept(GetWorldTime().GetTime()); for (unsigned i = 0; i < 7; i++) { character.AdjustCondition(static_cast<Condition>(i), -100); } character.ImproveSkill( SkillType::TotalHealth, SkillChange::HealMultiplier_100, 0x7fff); } else { // Start of Chapter 4, reduces health by 20% const int currentHealth = character.GetSkill(SkillType::TotalHealth); const auto reduction = ((currentHealth * -20) / 100) << 8; character.ImproveSkill( SkillType::TotalHealth, SkillChange::HealMultiplier_100, reduction); } } }
46,317
C++
.cpp
1,421
24.464462
134
0.595999
xavieran/BaKGL
39
2
32
GPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,364
worldItem.cpp
xavieran_BaKGL/bak/worldItem.cpp
#include "bak/worldItem.hpp" namespace BAK { auto LoadWorldTile(FileBuffer& fb) -> std::pair<std::vector<WorldItem>, glm::ivec2> { glm::ivec2 center{}; std::vector<WorldItem> items{}; while (!fb.AtEnd()) { unsigned itemType = fb.GetUint16LE(); unsigned xrot = fb.GetUint16LE(); unsigned yrot = fb.GetUint16LE(); unsigned zrot = fb.GetUint16LE(); unsigned xloc = fb.GetUint32LE(); unsigned yloc = fb.GetUint32LE(); unsigned zloc = fb.GetUint32LE(); if (itemType == 0) { center = {xloc, yloc}; } items.emplace_back( WorldItem{ itemType, glm::ivec3{xrot, yrot, zrot}, glm::ivec3{xloc, yloc, zloc}}); } return std::make_pair(items, center); } }
838
C++
.cpp
29
21.103448
52
0.5625
xavieran/BaKGL
39
2
32
GPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,365
ttmRunner.cpp
xavieran_BaKGL/bak/ttmRunner.cpp
#include "bak/ttmRunner.hpp" #include "bak/dialogSources.hpp" #include "bak/imageStore.hpp" #include "bak/screen.hpp" #include "bak/textureFactory.hpp" #include "com/assert.hpp" #include "com/logger.hpp" #include "graphics/types.hpp" namespace BAK { TTMRunner::TTMRunner() : mLogger{Logging::LogState::GetLogger("BAK::TTMRunner")} { } void TTMRunner::LoadTTM( std::string adsFile, std::string ttmFile) { mLogger.Debug() << "Loading ADS/TTM: " << adsFile << " " << ttmFile << "\n"; auto adsFb = BAK::FileBufferFactory::Get().CreateDataBuffer(adsFile); mSceneSequences = BAK::LoadSceneSequences(adsFb); auto ttmFb = BAK::FileBufferFactory::Get().CreateDataBuffer(ttmFile); mActions = BAK::LoadDynamicScenes(ttmFb); mCurrentSequence = 0; mCurrentSequenceScene = 0; auto nextTag = mSceneSequences[1][mCurrentSequence].mScenes[mCurrentSequenceScene].mDrawScene; mLogger.Debug() << "Next tag: " << nextTag << "\n"; mCurrentAction = FindActionMatchingTag(nextTag); } std::optional<BAK::SceneAction> TTMRunner::GetNextAction() { if (mCurrentAction == mActions.size()) { return std::nullopt; } auto action = mActions[mCurrentAction]; bool nextActionChosen = false; bool finishEarly = false; std::visit( overloaded{ [&](const BAK::Purge&){ AdvanceToNextScene(); nextActionChosen = true; }, [&](const BAK::GotoTag& sa){ // Hack til I figure out exactly how C31 works... if (sa.mTag == 4) { finishEarly = true; return; } mCurrentAction = FindActionMatchingTag(sa.mTag); nextActionChosen = true; }, [&](const auto&){} }, action ); if (finishEarly) { return std::nullopt; } if (nextActionChosen) { if (mCurrentAction == mActions.size()) { return std::nullopt; } action = mActions[mCurrentAction]; } mCurrentAction++; return action; } void TTMRunner::AdvanceToNextScene() { auto& currentScenes = mSceneSequences[1][mCurrentSequence].mScenes; mCurrentSequenceScene++; if (mCurrentSequenceScene == currentScenes.size()) { mCurrentSequenceScene = 0; mCurrentSequence++; } if (mCurrentSequence == mSceneSequences[1].size()) { mCurrentAction = mActions.size(); mCurrentSequence = 0; return; } auto nextTag = mSceneSequences[1][mCurrentSequence].mScenes[mCurrentSequenceScene].mDrawScene; mCurrentAction = FindActionMatchingTag(nextTag); } unsigned TTMRunner::FindActionMatchingTag(unsigned tag) { std::optional<unsigned> foundIndex{}; for (unsigned i = 0; i < mActions.size(); i++) { evaluate_if<BAK::SetScene>(mActions[i], [&](const auto& action) { if (action.mSceneNumber == tag) { foundIndex = i; } }); if (foundIndex) { return *foundIndex; } } return 0; } }
3,195
C++
.cpp
110
22.109091
98
0.61064
xavieran/BaKGL
39
2
32
GPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,366
tags.cpp
xavieran_BaKGL/bak/tags.cpp
#include "bak/tags.hpp" #include "com/logger.hpp" namespace BAK { void Tags::Load(FileBuffer& fb) { unsigned int n = fb.GetUint16LE(); for (unsigned int i = 0; i < n; i++) { unsigned int id = fb.GetUint16LE(); std::string name = fb.GetString(); mTags.emplace(id, name); } } std::optional<std::string> Tags::GetTag(Tag tag) const { const auto it = mTags.find(tag); if (it != mTags.end()) { return std::make_optional(it->second); } else { return std::nullopt; } } std::optional<Tag > Tags::FindTag(const std::string& tag) const { const auto it = std::find_if(mTags.begin(), mTags.end(), [&](const auto& it) { return it.second == tag; }); if (it != mTags.end()) { return std::make_optional(it->first); } else { return std::nullopt; } } void Tags::DumpTags() const { if (mTags.size() == 0) { Logging::LogDebug(__FUNCTION__) << "No Tags\n"; } for (const auto& [key, tag] : mTags) { Logging::LogDebug(__FUNCTION__) << " Key - " << key << " tag: " << tag << "\n"; } } }
1,175
C++
.cpp
53
17.169811
87
0.54219
xavieran/BaKGL
39
2
32
GPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,367
timeExpiringState.cpp
xavieran_BaKGL/bak/timeExpiringState.cpp
#include "bak/timeExpiringState.hpp" namespace BAK { std::ostream& operator<<(std::ostream& os, ExpiringStateType t) { switch (t) { using enum ExpiringStateType; case None: return os << "None"; case Light: return os << "Light"; case Spell: return os << "Spell"; case SetState: return os << "SetState"; case ResetState: return os << "ResetState"; default: return os << "UNKNOWN_TES!"; } } std::ostream& operator<<(std::ostream& os, const TimeExpiringState& t) { os << "TimeExpiringState{ Type: " << t.mType << " flags: " << std::hex << +t.mFlags << " data: " << t.mData << std::dec << " duration: " << t.mDuration << "}"; return os; } TimeExpiringState* AddTimeExpiringState( std::vector<TimeExpiringState>& storage, ExpiringStateType type, std::uint16_t data, std::uint8_t flags, Time duration) { if ((flags & 0x80) || (!(flags & 0x40))) { for (unsigned i = 0; i < storage.size(); i++) { auto& state = storage[i]; if (state.mType == type && state.mData == data) { if (flags & 0x80) { state.mDuration += duration; } else { state.mDuration = duration; } return &state; } } } if (storage.size() >= 0x14) { return nullptr; } else { storage.emplace_back(TimeExpiringState{type, flags, data, duration}); return &storage.back(); } } TimeExpiringState* AddLightTimeExpiringState(std::vector<TimeExpiringState>& storage, unsigned stateType, Time duration) { // PaletteRequiresChange(); // so that we make sure to update the lighting return AddTimeExpiringState(storage, ExpiringStateType::Light, stateType, 0x80, duration); } TimeExpiringState* AddSpellTimeExpiringState(std::vector<TimeExpiringState>& storage, unsigned spell, Time duration) { // PaletteRequiresChange(); // so that we make sure to update the lighting return AddTimeExpiringState(storage, ExpiringStateType::Spell, static_cast<std::uint16_t>(spell), 0x80, duration); } }
2,259
C++
.cpp
70
25.142857
121
0.595325
xavieran/BaKGL
39
2
32
GPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,368
hotspot.cpp
xavieran_BaKGL/bak/hotspot.cpp
#include "bak/hotspot.hpp" #include "com/ostream.hpp" #include "com/string.hpp" #include "graphics/glm.hpp" namespace BAK { std::string_view ToString(HotspotAction ha) { switch (ha) { case HotspotAction::UNKNOWN_0: return "UNKNOWN_0"; case HotspotAction::UNKNOWN_1: return "UNKNOWN_1"; case HotspotAction::DIALOG: return "Dialog"; case HotspotAction::EXIT: return "Exit"; case HotspotAction::GOTO: return "Goto"; case HotspotAction::BARMAID: return "Barmaid"; case HotspotAction::SHOP: return "Shop"; case HotspotAction::INN: return "Inn"; case HotspotAction::CONTAINER: return "Container"; case HotspotAction::LUTE: return "Lute"; case HotspotAction::REPAIR_2: return "REPAIR_2"; case HotspotAction::TELEPORT: return "Teleport"; case HotspotAction::UNKNOWN_C: return "UNKNOWN_C"; case HotspotAction::TEMPLE: return "Temple"; case HotspotAction::UNKNOWN_E: return "UNKNOWN_E"; case HotspotAction::CHAPTER_END: return "CHAPTER_END"; case HotspotAction::REPAIR: return "Repair"; case HotspotAction::UNKNOWN_X: return "UNKNOWN_X"; default: std::cerr << "Unknown!! " << +static_cast<unsigned>(ha) << std::endl; throw std::runtime_error("Unknown HotspotAction"); } } std::ostream& operator<<(std::ostream& os, HotspotAction ha) { return os << ToString(ha); } std::ostream& operator<<(std::ostream& os, const Hotspot& hs) { os << "Hotspot { id: " << hs.mHotspot << " topLeft: " << hs.mTopLeft << " dim: " << hs.mDimensions << " kw: " << hs.mKeyword << " act: " << hs.mAction << " arg1: " << std::hex << hs.mActionArg1 << " arg2: " << hs.mActionArg2 << " arg3: " << hs.mActionArg3 << " tip: " << hs.mTooltip << " dialog: " << hs.mDialog << " chapterMask: " << hs.mChapterMask << " | " << hs.mUnknown_1a << " | " << hs.mCheckEventState << std::dec << " }"; return os; } SceneHotspots::SceneHotspots(FileBuffer&& fb) { const auto& logger = Logging::LogState::GetLogger("BAK::SceneHotspots"); auto length = fb.GetUint16LE(); logger.Debug() << "Length: " << length << std::endl; const auto resource = fb.GetString(6); mSceneTTM = ToUpper(resource + ".TTM"); mSceneADS = ToUpper(resource + ".ADS"); logger.Debug() << "Scene Ref: " << mSceneTTM << std::endl; mUnknown_6 = fb.GetArray<6>(); logger.Debug() << "Unknown_6: " << std::hex << mUnknown_6 << std::dec << "\n"; mUnknown_c = fb.GetUint8(); logger.Debug() << "Unknown_C: " << std::hex << +mUnknown_c << std::dec << "\n"; mTempleIndex = fb.GetUint8(); logger.Debug() << "TempleIndex: " << std::hex << +mTempleIndex << std::dec << "\n"; mUnknown_e = fb.GetUint8(); logger.Debug() << "Unknown_E: " << std::hex << +mUnknown_e << std::dec << "\n"; mUnknown_f = fb.GetUint8(); logger.Debug() << "Unknown_F: " << std::hex << +mUnknown_f << std::dec << "\n"; mUnknown_10 = fb.GetUint8(); logger.Debug() << "Unknown_10: " << std::hex << +mUnknown_10 << std::dec << "\n"; mSong = fb.GetUint16LE(); logger.Debug() << "Song : " << mSong << "\n"; mUnknownIdx_13 = fb.GetUint16LE(); logger.Debug() << "Unknown_13: " << std::hex << +mUnknownIdx_13 << std::dec << "\n"; // For all towns, scene index1. mSceneIndex1 = fb.GetUint16LE(); logger.Debug() << "Scene index1: " << mSceneIndex1 << "\n"; const auto mUnkown_16 = fb.GetUint16LE(); logger.Debug() << "Unknown_16:" << mUnkown_16 << "\n"; mSceneIndex2 = fb.GetUint16LE(); logger.Debug() << "Scene index2: " << mSceneIndex2 << "\n"; auto numHotSpots = fb.GetUint16LE(); mFlavourText = fb.GetUint32LE(); logger.Debug() << "Hotspots: " << std::dec << numHotSpots << std::endl; logger.Debug() << "Flavour Text: " << std::hex << mFlavourText << std::endl; mUnknown_1f = fb.GetUint16LE(); logger.Debug() << "Unknown_1f:" << mUnknown_1f << "\n"; mUnknown_21 = fb.GetUint16LE(); logger.Debug() << "Unknown_21:" << mUnknown_21 << "\n"; mUnknown_23 = fb.GetUint16LE(); logger.Debug() << "Unknown_23:" << mUnknown_23 << "\n"; mUnknown_25 = fb.GetUint16LE(); logger.Debug() << "Unknown_25:" << mUnknown_25 << "\n"; std::vector<Hotspot> hotspots; for (unsigned i = 0; i < numHotSpots; i++) { auto x = fb.GetUint16LE(); auto y = fb.GetUint16LE(); auto w = fb.GetUint16LE(); auto h = fb.GetUint16LE(); logger.Debug() << "Hotspot #" << std::dec << i << std::endl; const auto chapterMask = fb.GetUint16LE(); logger.Debug() << "ChapterMask: " << std::hex << chapterMask << std::dec << std::endl; const auto keyword = fb.GetUint16LE(); const auto action = fb.GetUint8(); const auto unknown_D = fb.GetUint8(); logger.Debug() << "keyword: " << keyword << std::endl; logger.Debug() << "Action: " << +action << std::endl; logger.Debug() << "Unknown_D: " << +unknown_D << std::endl; const auto actionArg1 = fb.GetUint16LE(); const auto actionArg2 = fb.GetUint16LE(); const auto actionArg3 = fb.GetUint32LE(); logger.Debug() << "A1: " << actionArg1 << std::hex << " A2: " << actionArg2 << " A3: " << actionArg3 << std::dec << "\n"; std::uint32_t tooltip = fb.GetUint32LE(); logger.Debug() << "RightClick: " << std::hex << tooltip << std::endl; const auto unknown_1a = fb.GetUint32LE(); logger.Debug() << "Unknown_1a: " << std::hex << unknown_1a << std::dec << std::endl; std::uint32_t dialog = fb.GetUint32LE(); logger.Debug() << "LeftClick: " << std::hex << dialog << std::endl; const auto checkEventState = fb.GetUint16LE(); logger.Debug() << "CheckEventState: " << std::hex << checkEventState << std::dec << std::endl; //const auto unknown_24 = fb.GetUint8(); //const auto containerAddr = fb.GetUint8(); //logger.Debug() << "unknown_24: " << +unknown_24 << "\n"; //logger.Debug() << "containerAddr: " << +containerAddr << "\n"; hotspots.emplace_back( i, glm::vec<2, int>{x, y}, glm::vec<2, int>{w, h}, chapterMask, keyword, static_cast<HotspotAction>(action), unknown_D, actionArg1, actionArg2, actionArg3, KeyTarget{tooltip}, unknown_1a, KeyTarget{dialog}, checkEventState); } mHotspots = hotspots; for (auto& hs : hotspots) { logger.Debug() << hs << "\n"; } logger.Debug() << "ADS: " << mSceneADS << " TTM: " << mSceneTTM << " " << mSceneIndex1 << " " << mSceneIndex2 << "\n"; auto fb2 = FileBufferFactory::Get().CreateDataBuffer(mSceneADS); mAdsIndices = BAK::LoadSceneIndices(fb2); auto fb3 = FileBufferFactory::Get().CreateDataBuffer(mSceneTTM); mScenes = BAK::LoadScenes(fb3); } const Scene& SceneHotspots::GetScene( unsigned adsIndex, const GameState& gs) { const auto ttmIndex = mAdsIndices[adsIndex]; return mScenes[ttmIndex.mSceneIndex.GetTTMIndex(gs.GetChapter())]; } }
7,422
C++
.cpp
169
36.934911
137
0.57285
xavieran/BaKGL
39
2
32
GPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,369
ramp.cpp
xavieran_BaKGL/bak/ramp.cpp
#include "bak/ramp.hpp" namespace BAK { std::ostream& operator<<(std::ostream& os, const Ramp& ramp) { os << "Ramp {\n"; for (unsigned i = 0; i < ramp.mRamps.size(); i++) { os << " " << i << " ["; for (const auto& c : ramp.mRamps[i]) { os << " " << +c; } os << "]\n"; } os << "}"; return os; } Ramp LoadRamp(FileBuffer& fb) { Ramp ramp{}; while (fb.GetBytesLeft() > 0) { std::array<std::uint8_t, 256> colors{}; for (unsigned i = 0; i < 256; i++) { colors[i] = fb.GetUint8(); } ramp.mRamps.emplace_back(colors); } return ramp; } }
683
C++
.cpp
32
15.59375
60
0.465224
xavieran/BaKGL
39
2
32
GPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,370
skills.cpp
xavieran_BaKGL/bak/skills.cpp
#include "bak/skills.hpp" #include "com/logger.hpp" namespace BAK { std::string_view ToString(SkillType s) { switch (s) { case SkillType::Health: return "Health"; case SkillType::Stamina: return "Stamina"; case SkillType::Speed: return "Speed"; case SkillType::Strength: return "Strength"; case SkillType::Defense: return "Defense"; case SkillType::Crossbow: return "Crossbow"; case SkillType::Melee: return "Melee"; case SkillType::Casting: return "Casting"; case SkillType::Assessment: return "Assessment"; case SkillType::Armorcraft: return "Armorcraft"; case SkillType::Weaponcraft: return "Weaponcraft"; case SkillType::Barding: return "Barding"; case SkillType::Haggling: return "Haggling"; case SkillType::Lockpick: return "Lockpick"; case SkillType::Scouting: return "Scouting"; case SkillType::Stealth: return "Stealth"; case SkillType::TotalHealth: return "TotalHealth"; default: return "UnknownSkillType"; } } SkillType ToSkill(SkillTypeMask s) { using enum SkillTypeMask; switch (s) { case SkillTypeMask::Health: return SkillType::Health; case SkillTypeMask::Stamina: return SkillType::Stamina; case SkillTypeMask::Speed: return SkillType::Speed; case SkillTypeMask::Strength: return SkillType::Strength; case SkillTypeMask::Defense: return SkillType::Defense; case SkillTypeMask::Crossbow: return SkillType::Crossbow; case SkillTypeMask::Melee: return SkillType::Melee; case SkillTypeMask::Casting: return SkillType::Casting; case SkillTypeMask::Assessment: return SkillType::Assessment; case SkillTypeMask::Armorcraft: return SkillType::Armorcraft; case SkillTypeMask::Weaponcraft: return SkillType::Weaponcraft; case SkillTypeMask::Barding: return SkillType::Barding; case SkillTypeMask::Haggling: return SkillType::Haggling; case SkillTypeMask::Lockpick: return SkillType::Lockpick; case SkillTypeMask::Scouting: return SkillType::Scouting; case SkillTypeMask::Stealth: return SkillType::Stealth; case SkillTypeMask::TotalHealth: return SkillType::TotalHealth; default: assert(false); return SkillType::TotalHealth; } } std::ostream& operator<<(std::ostream& os, const Skill& s) { os << "{ Max: " << +s.mMax << " TrueSkill: " << +s.mTrueSkill << " Current: " << +s.mCurrent << " Experience: " << +s.mExperience << " Modifier: " << +s.mModifier << "["; if (s.mSelected) os << "*"; else os << " "; os << "] ["; if (s.mUnseenImprovement) os << "*"; else os << " "; os << "]}"; return os; } std::ostream& operator<<(std::ostream& os, const SkillAffector& p) { os << "SkillAffector{ Type: " << std::hex << p.mType << std::dec << " Skill: " << ToString(p.mSkill) << " Adjustment: " << p.mAdjustment << " Start: " << p.mStartTime << " End: " << p.mEndTime << "}"; return os; } std::ostream& operator<<(std::ostream& os, const Skills& s) { for (unsigned i = 0; i < Skills::sSkills; i++) { os << ToString(static_cast<SkillType>(i)) << " " << s.mSkills[i] << "\n"; } os << "SelectedSkillPool: " << s.mSelectedSkillPool << "\n"; return os; } unsigned CalculateEffectiveSkillValue( SkillType skillType, Skills& skills, const Conditions& conditions, const std::vector<SkillAffector>& skillAffectors, SkillRead skillRead) { if (skillType == SkillType::TotalHealth) { const auto health = CalculateEffectiveSkillValue( SkillType::Health, skills, conditions, skillAffectors, skillRead); const auto stamina = CalculateEffectiveSkillValue( SkillType::Stamina, skills, conditions, skillAffectors, skillRead); return health + stamina; } const auto skillIndex = static_cast<unsigned>(skillType); auto& skill = skills.GetSkill(skillType); if (skillRead == SkillRead::MaxSkill) { return skill.mMax; } else if (skillRead == SkillRead::TrueSkill) { return skill.mTrueSkill; } int skillCurrent = skill.mTrueSkill; if (skill.mModifier != 0) skillCurrent += skill.mModifier; if (skillCurrent < 0) skillCurrent = 0; for (const auto& affector : skillAffectors) { if (affector.mSkill == skillType) { if (skill.mMax == 0) continue; if (affector.mType & 0x100) { // notInCombat - 0x100 is typically spells that affect skill if (false) { continue; } } // The game checks if affectors are expired and resets them // but I think we should just do that when time increments // to save a dependency on current time here. // May need to revisit this when I do combat... // if (affector.mEndTime < worldClock.GetTime()) // { // erase(affector); // } // Ratio if ((affector.mType & 0x400) || (affector.mType & 0x800)) { skillCurrent = (skillCurrent * (affector.mAdjustment + 0x64)) / 0x64; } // Direct adjustment else { skillCurrent += affector.mAdjustment; } } } for (unsigned i = 0 ; i < 7; i++) { const auto condition = static_cast<Condition>(i); const auto conditionAmount = conditions.GetCondition(condition).Get(); const std::uint16_t skillBitOffset = 1 << skillIndex; if (conditionAmount != 0) { if (sConditionSkillEffect[i][2] & skillBitOffset) { auto effect = 0xffff - sConditionSkillEffect[i][3]; effect *= conditionAmount; effect /= 100; effect = 100 - effect; auto effectedSkill = (effect * skillCurrent) / 100; skillCurrent = effectedSkill; } // This doesn't do anything as far as I can tell because no // condition has fields 4 and 5 set. if (sConditionSkillEffect[i][4] & skillBitOffset) { auto effect = 0xffff - sConditionSkillEffect[i][5]; effect *= conditionAmount; effect /= 100; effect = 100 - effect; auto effectedSkill = (effect * skillCurrent) / 100; skillCurrent = effectedSkill; } } } const auto skillHealthEffect = sSkillHealthEffect[skillIndex]; if (skillHealthEffect != 0 && skillRead != SkillRead::NoHealthEffect) { const auto& health = skills.GetSkill(SkillType::Health); auto trueHealth = health.mTrueSkill; auto maxHealth = health.mMax; if (!(skillHealthEffect <= 1)) { trueHealth = (((skillHealthEffect - 1) * trueHealth) + maxHealth) / skillHealthEffect; } skillCurrent = (((skillCurrent * trueHealth) + maxHealth) - 1) / maxHealth; } if (skillCurrent > sSkillCaps[skillIndex]) skillCurrent = sSkillCaps[skillIndex]; if (skillCurrent > sSkillAbsMax) skillCurrent = sSkillAbsMax; if (skillCurrent < sEffectiveSkillMin[skillIndex]) skillCurrent = sEffectiveSkillMin[skillIndex]; skill.mCurrent = skillCurrent; return skillCurrent; } void DoImproveSkill( SkillType skillType, Skill& skill, SkillChange skillChangeType, unsigned multiplier, unsigned selectedSkillPool) { if (skill.mMax == 0) return; const auto skillIndex = static_cast<unsigned>(skillType); const auto initialSkillValue = skill.mTrueSkill; int experienceChange = 0; switch (skillChangeType) { case SkillChange::ExercisedSkill: { // Experience change scales with how close you are to 100 skill level const auto diff = sSkillExperienceVar1[skillIndex] - sSkillExperienceVar2[skillIndex]; experienceChange = ((diff * skill.mTrueSkill) / 100) + sSkillExperienceVar2[skillIndex]; if (multiplier != 0) experienceChange *= multiplier; } break; case SkillChange::DifferenceOfSkill: experienceChange = (100 - skill.mTrueSkill) * multiplier; break; case SkillChange::FractionOfSkill: experienceChange = (skill.mTrueSkill * multiplier) / 100; break; case SkillChange::Direct: experienceChange = multiplier; break; default: assert(false); break; } // di + 0x58 bool realChar = true; if (realChar) { if (skill.mSelected) { const auto bonus = (experienceChange * selectedSkillPool) / (sTotalSelectedSkillPool * 2); experienceChange += bonus; } } experienceChange += skill.mExperience; auto levels = experienceChange / 256; auto leftoverExperience = experienceChange % 256; skill.mExperience = leftoverExperience; if (levels < 0) { // fill this out... // offset 0x573 } skill.mTrueSkill = levels + skill.mTrueSkill; if (skill.mTrueSkill < sSkillMin[skillIndex]) skill.mTrueSkill = sSkillMin[skillIndex]; if (skill.mTrueSkill > sSkillMax[skillIndex]) skill.mTrueSkill = sSkillMax[skillIndex]; if (skill.mTrueSkill > skill.mMax) skill.mMax = skill.mTrueSkill; if (initialSkillValue != skill.mTrueSkill) skill.mUnseenImprovement = true; Logging::LogDebug(__FUNCTION__) << "SkillImproved: " << ToString(skillType) << " " << skill << "\n"; } signed DoAdjustHealth( Skills& skills, Conditions& conditions, signed healthChangePercent, signed multiplier) { Logging::LogDebug(__FUNCTION__) << "called with (" << healthChangePercent << " " << multiplier << ")\n"; auto& healthSkill = skills.GetSkill(SkillType::Health); auto& staminaSkill = skills.GetSkill(SkillType::Stamina); auto currentHealthAndStamina = healthSkill.mTrueSkill + staminaSkill.mTrueSkill; auto maxHealthAndStamina = healthSkill.mMax + staminaSkill.mMax; auto healthChange = (maxHealthAndStamina * healthChangePercent) / 0x64; Logging::LogDebug(__FUNCTION__) << " Current: " << currentHealthAndStamina << " Max: " << maxHealthAndStamina << "\n"; Logging::LogDebug(__FUNCTION__) << " HealthChange: " << healthChange << "\n"; // ovr131:03A3 bool isPlayerCharacter{true}; if (isPlayerCharacter) { // Near death inhibits healing const auto nearDeath = conditions.GetCondition(Condition::NearDeath).Get(); if (nearDeath != 0) { healthChange = (((0x64 - nearDeath) * 0x1E) / 0x64) + 1; } Logging::LogDebug(__FUNCTION__) << " NearDeath amt: " << +nearDeath << " efct on healthChange: " << healthChange << "\n"; } // ovr131:03c7 if (multiplier <= 0) { // ovr131:03f4 Logging::LogDebug(__FUNCTION__) << " Previous: " << currentHealthAndStamina << "\n"; currentHealthAndStamina += multiplier / 0x100; Logging::LogDebug(__FUNCTION__) << " Current: " << currentHealthAndStamina << "\n"; if (currentHealthAndStamina <= 0) { currentHealthAndStamina = 0; Logging::LogDebug(__FUNCTION__) << " NearDeath\n"; if (isPlayerCharacter) { conditions.AdjustCondition(skills, Condition::NearDeath, 100); // This doesn't always return the right results. e.g. // if just about to die due to sleeping, health ends up at // 1 rather than 0 } } } else { // ovr131:03ce Logging::LogDebug(__FUNCTION__) << __LINE__ << " Current: " << currentHealthAndStamina << "\n"; if (currentHealthAndStamina < healthChange) { currentHealthAndStamina += (multiplier / 0x100); Logging::LogDebug(__FUNCTION__) << __LINE__ << " New : " << currentHealthAndStamina << "\n"; if (currentHealthAndStamina > healthChange) { currentHealthAndStamina = healthChange; } } } Logging::LogDebug(__FUNCTION__) << " Final health: " << currentHealthAndStamina << "\n"; // ovr131:042b if (healthSkill.mMax >= currentHealthAndStamina) { staminaSkill.mTrueSkill = 0; healthSkill.mTrueSkill = currentHealthAndStamina; Logging::LogDebug(__FUNCTION__) << " No stamina left\n"; } else { staminaSkill.mTrueSkill = currentHealthAndStamina - healthSkill.mMax; healthSkill.mTrueSkill = healthSkill.mMax; Logging::LogDebug(__FUNCTION__) << " Some stamina left\n"; } return currentHealthAndStamina; } Skills::Skills(const SkillArray& skills, unsigned pool) : mSkills{skills}, mSelectedSkillPool{pool} {} const Skill& Skills::GetSkill(BAK::SkillType skill) const { const auto i = static_cast<unsigned>(skill); ASSERT(i < sSkills); return mSkills[i]; } Skill& Skills::GetSkill(BAK::SkillType skill) { const auto i = static_cast<unsigned>(skill); ASSERT(i < sSkills); return mSkills[i]; } void Skills::SetSkill(BAK::SkillType skillType, const Skill& skill) { const auto i = static_cast<unsigned>(skillType); mSkills[i] = skill; } void Skills::SetSelectedSkillPool(unsigned pool) { mSelectedSkillPool = pool; } void Skills::ToggleSkill(BAK::SkillType skillType) { auto& skill = GetSkill(skillType); skill.mSelected = !skill.mSelected; mSelectedSkillPool = CalculateSelectedSkillPool(); } void Skills::ClearUnseenImprovements() { for (auto& skill : mSkills) skill.mUnseenImprovement = false; } std::uint8_t Skills::CalculateSelectedSkillPool() const { const unsigned skillsSelected = std::accumulate( mSkills.begin(), mSkills.end(), 0, [](const auto sum, const auto& elem){ return sum + static_cast<unsigned>(elem.mSelected); }); return skillsSelected > 0 ? sTotalSelectedSkillPool / skillsSelected : 0; } void Skills::ImproveSkill( Conditions& conditions, SkillType skill, SkillChange skillChangeType, int multiplier) { if (skill == SkillType::TotalHealth) { DoAdjustHealth(*this, conditions, static_cast<int>(skillChangeType), multiplier); } else { DoImproveSkill( skill, GetSkill(skill), skillChangeType, multiplier, mSelectedSkillPool); } } Skills LoadSkills(FileBuffer& fb) { auto skills = Skills{}; for (unsigned i = 0; i < Skills::sSkills; i++) { const auto max = fb.GetUint8(); const auto trueSkill = fb.GetUint8(); const auto current = fb.GetUint8(); const auto experience = fb.GetUint8(); const auto modifier = fb.GetSint8(); skills.SetSkill(static_cast<SkillType>(i), Skill{ max, trueSkill, current, experience, modifier, false, false }); } return skills; } }
15,626
C++
.cpp
450
27.048889
122
0.616262
xavieran/BaKGL
39
2
32
GPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,371
IContainer.cpp
xavieran_BaKGL/bak/IContainer.cpp
#include "IContainer.hpp" #include "com/ostream.hpp" namespace BAK { std::string_view ToString(ContainerType type) { switch (type) { case ContainerType::Bag: return "Bag"; case ContainerType::CT1: return "CT1"; case ContainerType::Gravestone: return "Gravestone"; case ContainerType::Building: return "Building"; case ContainerType::Shop: return "Shop"; case ContainerType::Inn: return "Inn"; case ContainerType::TimirianyaHut: return "TimirianyaHut"; case ContainerType::Combat: return "Combat"; case ContainerType::Chest: return "Chest"; case ContainerType::FairyChest: return "FairyChest"; case ContainerType::EventChest: return "EventChest"; case ContainerType::Hole: return "Hole"; case ContainerType::Key: return "Key"; case ContainerType::Inv: return "Inv"; default: return "UnknownContainerType"; } } bool IContainer::IsShop() const { return GetContainerType() == BAK::ContainerType::Shop || GetContainerType() == BAK::ContainerType::Inn; } bool IContainer::HasLock() const { return CheckBitSet( static_cast<std::uint8_t>(GetContainerType()), 0x0); } }
1,172
C++
.cpp
36
28.472222
62
0.715678
xavieran/BaKGL
39
2
32
GPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,372
dialogChoice.cpp
xavieran_BaKGL/bak/dialogChoice.cpp
#include "bak/dialogChoice.hpp" #include "bak/spells.hpp" #include "com/logger.hpp" namespace BAK { std::string ToString(ActiveStateFlag f) { switch (f) { case ActiveStateFlag::Context: return "Context"; case ActiveStateFlag::Money: return "Money"; case ActiveStateFlag::CantAfford: return "CantAfford"; case ActiveStateFlag::Chapter: return "Chapter"; case ActiveStateFlag::NightTime: return "NightTime"; case ActiveStateFlag::DayTime: return "DayTime"; case ActiveStateFlag::TimeBetween: return "TimeBetween"; case ActiveStateFlag::SkillCheck: return "SkillCheck"; case ActiveStateFlag::ItemValue_753e: return "ItemValue_753e"; case ActiveStateFlag::Context_753f: return "Context_753f"; case ActiveStateFlag::Shop: return "Shop"; case ActiveStateFlag::Gambler: return "Gambler"; default: return "UnknownActiveStateFlag[" + std::to_string(static_cast<unsigned>(f)) + "]"; } } std::string_view ToString(ChoiceMask m) { switch (m) { case ChoiceMask::NoChoice: return "NoChoice"; case ChoiceMask::Conversation: return "Conversation"; case ChoiceMask::Query: return "Query"; case ChoiceMask::EventFlag: return "EventFlag"; case ChoiceMask::GameState: return "GameState"; case ChoiceMask::CustomState: return "CustomState"; case ChoiceMask::Inventory: return "Inventory"; case ChoiceMask::HaveNote: return "HaveNote"; case ChoiceMask::CastSpell: return "CastSpell"; case ChoiceMask::Random: return "Random"; case ChoiceMask::ComplexEvent: return "ComplexEvent"; default: return "UnknownChoiceMask"; }; } std::ostream& operator<<(std::ostream& os, const NoChoice& c) { os << ToString(ChoiceMask::NoChoice); return os; } std::ostream& operator<<(std::ostream& os, const ConversationChoice& c) { os << ToString(ChoiceMask::Conversation) << " " << std::hex << c.mEventPointer << " " << c.mKeyword << std::dec; return os; } std::ostream& operator<<(std::ostream& os, const QueryChoice& c) { os << ToString(ChoiceMask::Query) << " " << std::hex << c.mQueryIndex << std::dec << c.mKeyword; return os; } std::ostream& operator<<(std::ostream& os, const EventFlagChoice& c) { os << ToString(ChoiceMask::EventFlag) << "(" << std::hex << c.mEventPointer << std::dec << ")"; return os; } std::ostream& operator<<(std::ostream& os, const GameStateChoice& c) { os << ToString(ChoiceMask::GameState) << "(" << ToString(c.mState) << ")"; return os; } std::ostream& operator<<(std::ostream& os, Scenario s) { switch (s) { case Scenario::MortificationOfTheFlesh: os << "MortificationOfTheFlesh"; break; case Scenario::Plagued: os << "Plagued"; break; case Scenario::HaveSixSuitsOfArmor: os << "HaveSixSuitsOfArmor"; break; case Scenario::AllPartyArmorIsGoodCondition: os << "AllPartyArmorIsGoodCondition"; break; case Scenario::PoisonedDelekhanArmyChests: os << "PoisonedDelekhanArmyChests"; break; case Scenario::AnyCharacterSansWeapon: os << "AnyCharacterSansWeapon"; break; case Scenario::AnyCharacterHasNegativeCondition: os << "AnyCharacterHasNegativeCondition"; break; case Scenario::AnyCharacterIsUnhealthy: os << "AnyCharacterIsUnhealthy"; break; case Scenario::AllPartyMembersHaveNapthaMask: os << "AllPartyMembersHaveNapthaMask"; break; case Scenario::NormalFoodInArlieChest: os << "NormalFoodInArlieChest"; break; case Scenario::PoisonedFoodInArlieChest: os << "PoisonedFoodInArlieChest"; break; default: os << "Unknown(" << static_cast<unsigned>(s) << ")"; } return os; } std::ostream& operator<<(std::ostream& os, const CustomStateChoice& c) { os << ToString(ChoiceMask::CustomState) << "( scenario: " << c.mScenario << ")"; return os; } std::ostream& operator<<(std::ostream& os, const InventoryChoice& c) { os << ToString(ChoiceMask::Inventory) << "( item: " << c.mRequiredItem << ")"; return os; } std::ostream& operator<<(std::ostream& os, const ComplexEventChoice& c) { os << ToString(ChoiceMask::ComplexEvent) << " " << std::hex << c.mEventPointer << std::dec; return os; } std::ostream& operator<<(std::ostream& os, const CastSpellChoice& c) { os << ToString(ChoiceMask::CastSpell) << " " << c.mRequiredSpell << "\n"; return os; } std::ostream& operator<<(std::ostream& os, const HaveNoteChoice& c) { os << ToString(ChoiceMask::HaveNote) << "(" << c.mRequiredNote << ")"; return os; } std::ostream& operator<<(std::ostream& os, const RandomChoice& c) { os << ToString(ChoiceMask::Random) << "(" << c.mRange << ")"; return os; } std::ostream& operator<<(std::ostream& os, const UnknownChoice& c) { os << ToString(c.mChoiceCategory) << " " << std::hex << c.mEventPointer << std::dec << "\n"; return os; } std::ostream& operator<<(std::ostream& os, const Choice& c) { std::visit( [&os](const auto& choice) { os << choice; }, c); return os; } std::ostream& operator<<(std::ostream& os, const DialogChoice& d) { os << "DialogChoice{" << d.mChoice << " range: [" << d.mMin << ", " << d.mMax << "] -> " << std::hex << d.mTarget << std::dec << "}"; return os; } ChoiceMask CategoriseChoice(std::uint16_t state) { const auto CheckMask = [](const auto s, const ChoiceMask m) { return s <= static_cast<std::uint16_t>(m); }; for (const auto c : { ChoiceMask::NoChoice, ChoiceMask::Conversation, ChoiceMask::Query, ChoiceMask::EventFlag, ChoiceMask::GameState, ChoiceMask::CustomState, ChoiceMask::Inventory, ChoiceMask::HaveNote, ChoiceMask::CastSpell, ChoiceMask::Random, ChoiceMask::ComplexEvent}) { if (CheckMask(state, c)) return c; } return ChoiceMask::Unknown; } Choice CreateChoice(std::uint16_t state) { const auto mask = CategoriseChoice(state); switch (mask) { case ChoiceMask::NoChoice: return NoChoice{}; case ChoiceMask::Conversation: return ConversationChoice{state, ""}; case ChoiceMask::Query: return QueryChoice{state, ""}; case ChoiceMask::EventFlag: return EventFlagChoice{state}; case ChoiceMask::GameState: return GameStateChoice{static_cast<ActiveStateFlag>(state)}; case ChoiceMask::CustomState: return CustomStateChoice{ static_cast<Scenario>(state & ~0x9c40)}; case ChoiceMask::Inventory: return InventoryChoice{ static_cast<ItemIndex>(0xffff & (state + 0x3cb0))}; case ChoiceMask::ComplexEvent: return ComplexEventChoice{state}; case ChoiceMask::CastSpell: return CastSpellChoice{static_cast<unsigned>(state) - 0xcb21}; case ChoiceMask::HaveNote: return HaveNoteChoice{(static_cast<unsigned>(state) + 0x38c8) & 0xffff}; case ChoiceMask::Random: return RandomChoice{(static_cast<unsigned>(state) + 0x30f8) & 0xffff}; default: return UnknownChoice{mask, state}; } } DialogChoice::DialogChoice( std::uint16_t state, std::uint16_t min, std::uint16_t max, Target target) : mChoice{CreateChoice(state)}, mMin{min}, mMax{max}, mTarget{target} { } }
7,382
C++
.cpp
211
30.061611
105
0.666247
xavieran/BaKGL
39
2
32
GPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,373
aggregateFileProvider.cpp
xavieran_BaKGL/bak/file/aggregateFileProvider.cpp
#include "bak/file/aggregateFileProvider.hpp" #include "bak/file/fileProvider.hpp" #include "bak/file/packedFileProvider.hpp" namespace BAK::File { AggregateFileProvider::AggregateFileProvider(const std::vector<std::string>& searchPaths) : mProviders{} { mProviders.emplace_back( std::make_unique<FileDataProvider>(".")); for (const auto& path : searchPaths) { mProviders.emplace_back( std::make_unique<FileDataProvider>(path)); } mProviders.emplace( // Uncomment if we want to search in cwd first... std::next(mProviders.begin()), //mProviders.begin(), std::make_unique<PackedFileDataProvider>(*this)); } FileBuffer* AggregateFileProvider::GetDataBuffer(const std::string& fileName) { for (auto& provider : mProviders) { assert(provider); auto* fb = provider->GetDataBuffer(fileName); if (fb != nullptr) { return fb; } } return nullptr; } }
1,002
C++
.cpp
35
23.057143
89
0.662148
xavieran/BaKGL
39
2
32
GPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,374
util.cpp
xavieran_BaKGL/bak/file/util.cpp
#include "bak/file/util.hpp" #include "com/logger.hpp" namespace BAK::File { unsigned GetStreamSize(std::ifstream& ifs) { ifs.ignore( std::numeric_limits<std::streamsize>::max() ); std::streamsize length = ifs.gcount(); ifs.clear(); ifs.seekg( 0, std::ios_base::beg ); return static_cast<unsigned>(length); } FileBuffer CreateFileBuffer(const std::string& fileName) { Logging::LogInfo(__FUNCTION__) << "Opening: " << fileName << std::endl; std::ifstream in{}; in.open(fileName, std::ios::in | std::ios::binary); if (!in.good()) { std::cerr << "Failed to open file: " << fileName<< std::endl; std::stringstream ss{}; ss << __FILE__ << ":" << __LINE__ << " " << __FUNCTION__ << " OpenError!"; Logging::LogFatal("FileBuffer") << ss.str() << std::endl; throw std::runtime_error(ss.str()); } FileBuffer fb{GetStreamSize(in)}; fb.Load(in); in.close(); return fb; } }
968
C++
.cpp
30
27.7
82
0.602578
xavieran/BaKGL
39
2
32
GPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,375
packedResourceFile.cpp
xavieran_BaKGL/bak/file/packedResourceFile.cpp
#include "bak/file/packedResourceFile.hpp" #include "bak/file/IDataBufferProvider.hpp" #include "com/logger.hpp" namespace BAK::File { ResourceIndex::ResourceIndex( FileBuffer& resourceIndex) : mPackedResourceName{}, mResourceIndexData{} { const auto rmfMajorVersion = resourceIndex.GetUint32LE(); const auto rmfMinorVersion = resourceIndex.GetUint16LE(); mPackedResourceName = resourceIndex.GetString(sFilenameLength); const auto numPackedResources = resourceIndex.GetUint16LE(); Logging::LogDebug("BAK::ResourceIndex") << "RMF Version (" << rmfMajorVersion << ", " << rmfMinorVersion << ") ResourceFile: " << mPackedResourceName << " Resources: " << numPackedResources << "\n"; for (unsigned i = 0; i < numPackedResources; i++) { const unsigned hashKey = resourceIndex.GetUint32LE(); const std::streamoff offset = resourceIndex.GetUint32LE(); mResourceIndexData.emplace_back(ResourceIndexData{hashKey, offset}); //packedResource.Seek(offset); //const auto resourceName = packedResource.GetString(sFilenameLength); //const auto resourceSize = packedResource.GetUint32LE(); //Logging::LogDebug("BAK::ResourceIndex") << "Resource: " << resourceName << " hash: " << std::hex << hashKey // << std::dec << " offset: " << offset << " size: " << resourceSize << "\n"; //mResourceIndexMap.emplace( // resourceName, // ResourceIndexData{ // hashKey, // offset + sFilenameLength + 4, // resourceSize}); } } const std::string& ResourceIndex::GetPackedResourceFile() const { return mPackedResourceName; } const std::vector<ResourceIndex::ResourceIndexData>& ResourceIndex::GetResourceIndex() const { return mResourceIndexData; } }
1,841
C++
.cpp
44
36.5
117
0.678971
xavieran/BaKGL
39
2
32
GPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,376
fileBuffer.cpp
xavieran_BaKGL/bak/file/fileBuffer.cpp
#include "bak/file/fileBuffer.hpp" #include "com/logger.hpp" #include "com/path.hpp" #include <filesystem> #include <functional> #include <iomanip> #include <iostream> #include <map> #include <cassert> #include <cstring> #include <limits> #include <sstream> #include <SDL2/SDL_endian.h> namespace BAK { FileBuffer::FileBuffer( std::uint8_t* buf, std::uint8_t* current, std::uint32_t size, std::uint32_t nb) : mBuffer{buf}, mCurrent{current}, mSize{size}, mNextBit{nb}, mOwnBuffer{false} { } FileBuffer::FileBuffer(const unsigned n) : mBuffer{std::invoke([n](){ auto buf = new uint8_t[n]; memset(buf, 0, n); return buf; })}, mCurrent{mBuffer}, mSize{n}, mNextBit{0}, mOwnBuffer{true} { } FileBuffer::FileBuffer(FileBuffer&& fb) noexcept { (*this) = std::move(fb); } FileBuffer& FileBuffer::operator=(FileBuffer&& fb) noexcept { bool wasOwnBuffer = fb.mOwnBuffer; fb.mOwnBuffer = false; mBuffer = fb.mBuffer; mCurrent = fb.mCurrent; mSize = fb.mSize; mNextBit = fb.mNextBit; mOwnBuffer = wasOwnBuffer; return *this; } FileBuffer::~FileBuffer() { if (mBuffer && mOwnBuffer) { delete[] mBuffer; } } void FileBuffer::CopyFrom(FileBuffer *buf, const unsigned n) { if (mBuffer && n && (mCurrent + n <= mBuffer + mSize)) { buf->GetData(mCurrent, n); mCurrent += n; } } void FileBuffer::CopyTo(FileBuffer *buf, const unsigned n) { if (mBuffer && n && (mCurrent + n <= mBuffer + mSize)) { buf->PutData(mCurrent, n); mCurrent += n; } } void FileBuffer::Fill(FileBuffer *buf) { if (mBuffer) { mCurrent = mBuffer; buf->GetData(mBuffer, std::min(mSize, buf->GetSize())); } } FileBuffer FileBuffer::Find(std::uint32_t tag) const { auto *search = mBuffer; for (; search < (mBuffer + mSize - sizeof(std::uint32_t)); search++) { auto current = *reinterpret_cast<std::uint32_t*>(search); if (current == tag) { search += 4; const auto mBufferSize = *reinterpret_cast<std::uint32_t*>(search); search += 4; return FileBuffer{ search, search, mBufferSize, 0}; } } std::stringstream ss{}; ss << "Tag not found: " << std::hex << tag; throw std::runtime_error(ss.str()); } FileBuffer FileBuffer::MakeSubBuffer(std::uint32_t offset, std::uint32_t size) const { if (mSize < offset + size) { std::stringstream ss{}; ss << __FILE__ << ":" << __LINE__ << " " << __FUNCTION__ << " Requested new FileBuffer larger than available size: (" << offset << ", " << size << ") my size: " << mSize; Logging::LogFatal("FileBuffer") << ss.str() << std::endl; throw std::runtime_error(ss.str()); } return FileBuffer{ mBuffer + offset, mBuffer + offset, size, 0}; } void FileBuffer::Load(std::ifstream &ifs) { if (ifs.is_open()) { mCurrent = mBuffer; ifs.read((char *)mBuffer, mSize); if (ifs.fail()) { std::stringstream ss{}; ss << __FILE__ << ":" << __LINE__ << " " << __FUNCTION__ << " IOError!"; Logging::LogFatal("FileBuffer") << ss.str() << std::endl; throw std::runtime_error(ss.str()); } } else { std::stringstream ss{}; ss << __FILE__ << ":" << __LINE__ << " " << __FUNCTION__ << " OpenError!"; Logging::LogFatal("FileBuffer") << ss.str() << std::endl; throw std::runtime_error(ss.str()); } } void FileBuffer::Save(std::ofstream &ofs) { if (ofs.is_open()) { mCurrent = mBuffer; ofs.write((char *)mBuffer, mSize); if (ofs.fail()) { std::stringstream ss{}; ss << __FILE__ << ":" << __LINE__ << " " << __FUNCTION__ << " IOError!"; Logging::LogFatal("FileBuffer") << ss.str() << std::endl; throw std::runtime_error(ss.str()); } } else { std::stringstream ss{}; ss << __FILE__ << ":" << __LINE__ << " " << __FUNCTION__ << " OpenError!"; Logging::LogFatal("FileBuffer") << ss.str() << std::endl; throw std::runtime_error(ss.str()); } } void FileBuffer::Save(std::ofstream &ofs, const unsigned n) { if (ofs.is_open()) { if (n <= mSize) { mCurrent = mBuffer; ofs.write((char *)mBuffer, n); if (ofs.fail()) { std::stringstream ss{}; ss << __FILE__ << ":" << __LINE__ << " " << __FUNCTION__ << " IOError!"; Logging::LogFatal("FileBuffer") << ss.str() << std::endl; throw std::runtime_error(ss.str()); } } else { std::stringstream ss{}; ss << __FILE__ << ":" << __LINE__ << " " << __FUNCTION__ << " BufferEmpty!"; Logging::LogFatal("FileBuffer") << ss.str() << std::endl; throw std::runtime_error(ss.str()); } } else { std::stringstream ss{}; ss << __FILE__ << ":" << __LINE__ << " " << __FUNCTION__ << " OpenError!"; Logging::LogFatal("FileBuffer") << ss.str() << std::endl; throw std::runtime_error(ss.str()); } } void FileBuffer::Dump(const unsigned n) { if (n == 0) return; Dump(std::cout, n); } void FileBuffer::DumpAndSkip(const unsigned n) { if (n == 0) return; Dump(n); Skip(n); } void FileBuffer::Dump(std::ostream& os, const unsigned n) { uint8_t* tmp = mCurrent; unsigned count = 0; os << std::setbase(16) << std::setfill('0') << std::setw(8) << count << ": "; while ((tmp < (mBuffer + mSize)) && ((tmp < (mCurrent + n)) || (n == 0))) { os << std::setw(2) << (unsigned)*tmp++ << " "; if ((++count & 0x1f) == 0) { os << std::endl << std::setw(8) << count << ": "; } else if ((count & 0x07) == 0) { os << "| "; } } os << std::setbase(10) << std::setfill(' ') << std::endl; } void FileBuffer::Seek(const unsigned n) { if ((mCurrent) && (n <= mSize)) { mCurrent = mBuffer + n; } else { return; std::stringstream ss{}; ss << __FILE__ << ":" << __LINE__ << " " << __FUNCTION__ << " Tried to seek to: " << n << " but size is only: " << mSize << "!\n"; Logging::LogFatal("FileBuffer") << ss.str() << std::endl; throw std::runtime_error(ss.str()); } } void FileBuffer::Skip(const int n) { if ((mCurrent) && (mCurrent + n <= mBuffer + mSize)) { mCurrent += n; } } void FileBuffer::SkipBits() { if (mNextBit) { Skip(1); mNextBit = 0; } } typedef union _HashTableEntry { uint32_t code; struct { uint16_t prefix; uint8_t append; } entry; } HashTableEntry; unsigned FileBuffer::CompressLZW(FileBuffer *result) { try { std::map<uint32_t, uint16_t> hashtable; unsigned n_bits = 9; unsigned free_entry = 257; unsigned bitpos = 0; HashTableEntry hte; hte.entry.prefix = GetUint8(); while (!AtEnd() && !result->AtEnd()) { hte.entry.append = GetUint8(); std::map<uint32_t, uint16_t>::iterator it = hashtable.find(hte.code); if (it == hashtable.end()) { result->PutBits(hte.entry.prefix, n_bits); bitpos += n_bits; hashtable.insert(std::pair<uint32_t, uint16_t>(hte.code, free_entry)); hte.entry.prefix = hte.entry.append; free_entry++; if (free_entry >= (unsigned)(1 << n_bits)) { if (n_bits < 12) { n_bits++; } else { hashtable.clear(); free_entry = 256; result->PutBits(free_entry, n_bits); result->SkipBits(); result->Skip((((bitpos-1)+((n_bits<<3)-(bitpos-1+(n_bits<<3))%(n_bits<<3)))-bitpos)>>3); n_bits = 9; bitpos = 0; } } } else { hte.entry.prefix = it->second; } } hashtable.clear(); unsigned res = result->GetBytesDone(); result->Rewind(); return res; } catch (std::exception& e) { Logging::LogFatal("FileBuffer") << __FUNCTION__ << " " << e.what() << std::endl; throw; } return 0; } unsigned FileBuffer::CompressLZSS(FileBuffer *result) { try { uint8_t *data = GetCurrent(); uint8_t *current = GetCurrent(); uint8_t *codeptr = result->GetCurrent(); uint8_t byte = GetUint8(); uint8_t code = 0; uint8_t mask = 0; while (!AtEnd() && !result->AtEnd()) { if (!mask) { *codeptr = code; codeptr = result->GetCurrent(); result->Skip(1); code = 0; mask = 0x01; } unsigned off = 0; unsigned len = 0; uint8_t *ptr = current; while (ptr > data) { ptr--; if (*ptr == byte) { off = ptr - data; len = 1; while ((current + len < mBuffer + mSize) && (ptr[len] == current[len])) { len++; } } } if (len < 5) { code |= mask; result->PutUint8(byte); } else { result->PutUint16LE(off); result->PutUint8(len - 5); Skip(len - 1); } current = GetCurrent(); byte = GetUint8(); mask <<= 1; } *codeptr = code; unsigned res = result->GetBytesDone(); result->Rewind(); return res; } catch (std::exception& e) { Logging::LogFatal("FileBuffer") << __FUNCTION__ << " " << e.what() << std::endl; throw; } return 0; } unsigned FileBuffer::CompressRLE(FileBuffer *result) { try { uint8_t *skipptr = GetCurrent(); uint8_t byte = 0; uint8_t next = GetUint8(); unsigned count; unsigned skipped = 0; while (!AtEnd() && !result->AtEnd()) { count = 1; do { byte = next; next = GetUint8(); count++; } while (!AtEnd() && (next == byte)); if (next != byte) { count--; } if (count > 3) { if (skipped > 0) { while (skipped > 0) { unsigned n; if (skipped > 127) { n = 127; } else { n = skipped & 0x7f; } result->PutUint8(n); result->PutData(skipptr, n); skipped -= n; skipptr += n; } } while (count > 3) { unsigned n; if (count > 127) { n = 127; } else { n = count & 0x7f; } result->PutUint8(n | 0x80); result->PutUint8(byte); count -= n; } skipped = count; skipptr = GetCurrent() - skipped - 1; } else { skipped += count; } } if (next != byte) { skipped++; } if (skipped > 0) { Skip(-skipped); while (skipped > 0) { unsigned n = skipped & 0x7f; result->PutUint8(n); result->CopyFrom(this, n); skipped -= n; } } unsigned res = result->GetBytesDone(); result->Rewind(); return res; } catch (std::exception& e) { Logging::LogFatal("FileBuffer") << __FUNCTION__ << " " << e.what() << std::endl; throw; } return 0; } unsigned FileBuffer::Compress(FileBuffer *result, const unsigned method) { switch (method) { case COMPRESSION_LZW: return CompressLZW(result); break; case COMPRESSION_LZSS: return CompressLZSS(result); break; case COMPRESSION_RLE: return CompressRLE(result); break; default: std::stringstream ss{}; ss << __FILE__ << ":" << __LINE__ << " " << __FUNCTION__ << " CompressionError!"; Logging::LogFatal("FileBuffer") << ss.str() << std::endl; throw std::runtime_error(ss.str()); break; } } typedef struct _CodeTableEntry { uint16_t prefix; uint8_t append; } CodeTableEntry; unsigned FileBuffer::DecompressLZW(FileBuffer *result) { try { CodeTableEntry *codetable = new CodeTableEntry[4096]; uint8_t *decodestack = new uint8_t[4096]; uint8_t *stackptr = decodestack; unsigned n_bits = 9; unsigned free_entry = 257; unsigned oldcode = GetBits(n_bits); unsigned lastbyte = oldcode; unsigned bitpos = 0; result->PutUint8(oldcode); while (!AtEnd() && !result->AtEnd()) { unsigned newcode = GetBits(n_bits); bitpos += n_bits; if (newcode == 256) { SkipBits(); Skip((((bitpos-1)+((n_bits<<3)-(bitpos-1+(n_bits<<3))%(n_bits<<3)))-bitpos)>>3); n_bits = 9; free_entry = 256; bitpos = 0; } else { unsigned code = newcode; if (code >= free_entry) { *stackptr++ = lastbyte; code = oldcode; } while (code >= 256) { *stackptr++ = codetable[code].append; code = codetable[code].prefix; } *stackptr++ = code; lastbyte = code; while (stackptr > decodestack) { result->PutUint8(*--stackptr); } if (free_entry < 4096) { codetable[free_entry].prefix = oldcode; codetable[free_entry].append = lastbyte; free_entry++; if ((free_entry >= (unsigned)(1 << n_bits)) && (n_bits < 12)) { n_bits++; bitpos = 0; } } oldcode = newcode; } } delete[] decodestack; delete[] codetable; unsigned res = result->GetBytesDone(); result->Rewind(); return res; } catch (std::exception& e) { Logging::LogFatal("FileBuffer") << __FUNCTION__ << " " << e.what() << std::endl; throw; } return 0; } unsigned FileBuffer::DecompressLZSS(FileBuffer *result) { try { uint8_t *data = result->GetCurrent(); uint8_t code = 0; uint8_t mask = 0; while (!AtEnd() && !result->AtEnd()) { if (!mask) { code = GetUint8(); mask = 0x01; } if (code & mask) { result->PutUint8(GetUint8()); } else { unsigned off = GetUint16LE(); unsigned len = GetUint8() + 5; result->PutData(data + off, len); } mask <<= 1; } unsigned res = result->GetBytesDone(); result->Rewind(); return res; } catch (std::exception& e) { Logging::LogFatal("FileBuffer") << __FUNCTION__ << " " << e.what() << std::endl; throw; } return 0; } unsigned FileBuffer::DecompressRLE(FileBuffer *result) { try { while (!AtEnd() && !result->AtEnd()) { uint8_t control = GetUint8(); if (control & 0x80) { result->PutData(GetUint8(), control & 0x7f); } else { result->CopyFrom(this, control); } } unsigned res = result->GetBytesDone(); result->Rewind(); return res; } catch (std::exception& e) { Logging::LogFatal("FileBuffer") << __FUNCTION__ << " " << e.what() << std::endl; throw; } return 0; } unsigned FileBuffer::Decompress(FileBuffer *result, const unsigned method) { switch (method) { case COMPRESSION_LZW: if ((GetUint8() != 0x02) || (GetUint32LE() != result->GetSize())) { std::stringstream ss{}; ss << __FILE__ << ":" << __LINE__ << " " << __FUNCTION__ << " DataCorruption!"; Logging::LogFatal("FileBuffer") << ss.str() << std::endl; throw std::runtime_error(ss.str()); } return DecompressLZW(result); break; case COMPRESSION_LZSS: return DecompressLZSS(result); break; case COMPRESSION_RLE: return DecompressRLE(result); break; default: std::stringstream ss{}; ss << __FILE__ << ":" << __LINE__ << " " << __FUNCTION__ << " CompressionError!"; Logging::LogFatal("FileBuffer") << ss.str() << std::endl; throw std::runtime_error(ss.str()); break; } } bool FileBuffer::AtEnd() const { return (mCurrent >= mBuffer + mSize); } unsigned FileBuffer::GetSize() const { return mSize; } unsigned FileBuffer::GetBytesDone() const { return (mCurrent - mBuffer); } unsigned FileBuffer::GetBytesLeft() const { return (mBuffer + mSize - mCurrent); } uint8_t * FileBuffer::GetCurrent() const { return mCurrent; } unsigned FileBuffer::GetNextBit() const { return mNextBit; } void FileBuffer::Rewind() { mCurrent = mBuffer; } unsigned FileBuffer::Tell() { return mCurrent - mBuffer; } uint8_t FileBuffer::Peek() { return *mCurrent; } uint8_t FileBuffer::GetUint8() { uint8_t n; GetData(&n, 1); return n; } uint16_t FileBuffer::GetUint16LE() { uint16_t n; GetData(&n, 2); return SDL_SwapLE16(n); } uint16_t FileBuffer::GetUint16BE() { uint16_t n; GetData(&n, 2); return SDL_SwapBE16(n); } uint32_t FileBuffer::GetUint32LE() { uint32_t n; GetData(&n, 4); return SDL_SwapLE32(n); } uint32_t FileBuffer::GetUint32BE() { uint32_t n; GetData(&n, 4); return SDL_SwapBE32(n); } int8_t FileBuffer::GetSint8() { int8_t n; GetData(&n, 1); return n; } int16_t FileBuffer::GetSint16LE() { int16_t n; GetData(&n, 2); return SDL_SwapLE16(n); } int16_t FileBuffer::GetSint16BE() { int16_t n; GetData(&n, 2); return SDL_SwapBE16(n); } int32_t FileBuffer::GetSint32LE() { int32_t n; GetData(&n, 4); return SDL_SwapLE32(n); } int32_t FileBuffer::GetSint32BE() { int32_t n; GetData(&n, 4); return SDL_SwapBE32(n); } std::string FileBuffer::GetString() { if (mCurrent) { std::string s((char *)mCurrent); if ((mCurrent + s.length() + 1) <= (mBuffer + mSize)) { mCurrent += s.length() + 1; return s; } else { std::stringstream ss{}; ss << __FILE__ << ":" << __LINE__ << " " << __FUNCTION__ << " BufferEmpty!"; Logging::LogFatal("FileBuffer") << ss.str() << std::endl; throw std::runtime_error(ss.str()); } } return ""; } std::string FileBuffer::GetString(const unsigned len) { if ((mCurrent) && (mCurrent + len <= mBuffer + mSize)) { std::string s((char *)mCurrent); mCurrent += len; return s; } else { std::stringstream ss{}; ss << __FILE__ << ":" << __LINE__ << " " << __FUNCTION__ << " BufferEmpty!"; Logging::LogFatal("FileBuffer") << ss.str() << std::endl; throw std::runtime_error(ss.str()); } return ""; } void FileBuffer::GetData(void *data, const unsigned n) { if ((mCurrent + n) <= (mBuffer + mSize)) { memcpy(data, mCurrent, n); mCurrent += n; } else { std::cerr << "Requested: " << n << " but @" << (mCurrent - mBuffer) << " mSize: " << mSize << " @: " << std::hex << static_cast<void*>(mCurrent + n) << " to " << " @: " << std::hex << static_cast<void*>(mBuffer + mSize) << std::endl; std::stringstream ss{}; ss << __FILE__ << ":" << __LINE__ << " " << __FUNCTION__ << " BufferEmpty!"; Logging::LogFatal("FileBuffer") << ss.str() << std::endl; throw std::runtime_error(ss.str()); } } unsigned FileBuffer::GetBits(const unsigned n) { if (mCurrent + ((mNextBit + n + 7)/8) <= mBuffer + mSize) { unsigned x = 0; for (unsigned i = 0; i < n; i++) { if (*mCurrent & (1 << mNextBit)) { x += (1 << i); } mNextBit++; if (mNextBit > 7) { mCurrent++; mNextBit = 0; } } return x; } else { std::stringstream ss{}; ss << __FILE__ << ":" << __LINE__ << " " << __FUNCTION__ << " BufferEmpty!"; Logging::LogFatal("FileBuffer") << ss.str() << std::endl; throw std::runtime_error(ss.str()); } } void FileBuffer::PutUint8(const uint8_t x) { uint8_t xx = x; PutData(&xx, 1); } void FileBuffer::PutUint16LE(const uint16_t x) { uint16_t xx = SDL_SwapLE16(x); PutData(&xx, 2); } void FileBuffer::PutUint16BE(const uint16_t x) { uint16_t xx = SDL_SwapBE16(x); PutData(&xx, 2); } void FileBuffer::PutUint32LE(const uint32_t x) { uint32_t xx = SDL_SwapLE32(x); PutData(&xx, 4); } void FileBuffer::PutUint32BE(const uint32_t x) { uint32_t xx = SDL_SwapBE32(x); PutData(&xx, 4); } void FileBuffer::PutSint8(const int8_t x) { int8_t xx = x; PutData(&xx, 1); } void FileBuffer::PutSint16LE(const int16_t x) { int16_t xx = SDL_SwapLE16(x); PutData(&xx, 2); } void FileBuffer::PutSint16BE(const int16_t x) { int16_t xx = SDL_SwapBE16(x); PutData(&xx, 2); } void FileBuffer::PutSint32LE(const int32_t x) { int32_t xx = SDL_SwapLE32(x); PutData(&xx, 4); } void FileBuffer::PutSint32BE(const int32_t x) { int32_t xx = SDL_SwapBE32(x); PutData(&xx, 4); } void FileBuffer::PutString(const std::string s) { if ((mCurrent) && (mCurrent + s.length() + 1 <= mBuffer + mSize)) { strncpy((char *)mCurrent, s.c_str(), s.length() + 1); mCurrent += s.length() + 1; } else { std::stringstream ss{}; ss << __FILE__ << ":" << __LINE__ << " " << __FUNCTION__ << " BufferFull!"; Logging::LogFatal("FileBuffer") << ss.str() << std::endl; throw std::runtime_error(ss.str()); } } void FileBuffer::PutString(const std::string s, const unsigned len) { if ((mCurrent) && (mCurrent + len <= mBuffer + mSize)) { memset(mCurrent, 0, len); strncpy((char *)mCurrent, s.c_str(), len); mCurrent += len; } else { std::stringstream ss{}; ss << __FILE__ << ":" << __LINE__ << " " << __FUNCTION__ << " BufferFull!"; Logging::LogFatal("FileBuffer") << ss.str() << std::endl; throw std::runtime_error(ss.str()); } } void FileBuffer::PutData(void *data, const unsigned n) { if (mCurrent + n <= mBuffer + mSize) { memcpy(mCurrent, data, n); mCurrent += n; } else { std::stringstream ss{}; ss << __FILE__ << ":" << __LINE__ << " " << __FUNCTION__ << " BufferFull!"; Logging::LogFatal("FileBuffer") << ss.str() << std::endl; throw std::runtime_error(ss.str()); } } void FileBuffer::PutData(const uint8_t x, const unsigned n) { if (mCurrent + n <= mBuffer + mSize) { memset(mCurrent, x, n); mCurrent += n; } else { std::stringstream ss{}; ss << __FILE__ << ":" << __LINE__ << " " << __FUNCTION__ << " BufferFull!"; Logging::LogFatal("FileBuffer") << ss.str() << std::endl; throw std::runtime_error(ss.str()); } } void FileBuffer::PutBits(const unsigned x, const unsigned n) { if (mCurrent + ((mNextBit + n + 7)/8) <= mBuffer + mSize) { for (unsigned i = 0; i < n; i++) { if (x & (1 << i)) { *mCurrent |= (1 << mNextBit); } else { *mCurrent &= ~(1 << mNextBit); } mNextBit++; if (mNextBit > 7) { mCurrent++; mNextBit = 0; } } } else { std::stringstream ss{}; ss << __FILE__ << ":" << __LINE__ << " " << __FUNCTION__ << " BufferFull!"; Logging::LogFatal("FileBuffer") << ss.str() << std::endl; throw std::runtime_error(ss.str()); } } }
26,390
C++
.cpp
1,056
17.042614
138
0.474699
xavieran/BaKGL
39
2
32
GPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,377
fileProvider.cpp
xavieran_BaKGL/bak/file/fileProvider.cpp
#include "bak/file/fileProvider.hpp" #include "bak/file/util.hpp" #include "com/logger.hpp" namespace BAK::File { FileDataProvider::FileDataProvider(const std::string& basePath) : mBasePath{basePath} {} bool FileDataProvider::DataFileExists(const std::string& path) const { return mCache.contains(path) || std::filesystem::exists(mBasePath / path); } FileBuffer* FileDataProvider::GetDataBuffer(const std::string& path) { Logging::LogSpam("FileDataProvider") << "Searching for file: " << path << " in directory [" << mBasePath.string() << "]" << std::endl; if (DataFileExists(path)) { if (!mCache.contains(path)) { const auto [it, emplaced] = mCache.emplace(path, CreateFileBuffer((mBasePath / path).string())); assert(emplaced); } return &mCache.at(path); } else { return nullptr; } } }
912
C++
.cpp
32
23.625
108
0.652523
xavieran/BaKGL
39
2
32
GPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,378
packedFileProvider.cpp
xavieran_BaKGL/bak/file/packedFileProvider.cpp
#include "bak/file/packedFileProvider.hpp" #include "bak/file/packedResourceFile.hpp" namespace BAK::File { PackedFileDataProvider::PackedFileDataProvider(IDataBufferProvider& dataProvider) : mCache{}, mLogger{Logging::LogState::GetLogger("PackedFileDataProvider")} { auto* resourceIndexFb = dataProvider.GetDataBuffer(ResourceIndex::sFilename); if (resourceIndexFb == nullptr) { mLogger.Warn() << "Could not find resource index file [" << ResourceIndex::sFilename << "]. Will not use packed resource file for data." << std::endl; return; } auto resourceIndex = ResourceIndex{*resourceIndexFb}; auto* packedResource = dataProvider.GetDataBuffer(resourceIndex.GetPackedResourceFile()); if (packedResource == nullptr) { mLogger.Warn() << "Could not find packed resource file [" << resourceIndex.GetPackedResourceFile() << "]. Will not use packed resource file for data." << std::endl; return; } for (const auto& index : resourceIndex.GetResourceIndex()) { packedResource->Seek(index.mOffset); const auto resourceName = packedResource->GetString(ResourceIndex::sFilenameLength); const auto resourceSize = packedResource->GetUint32LE(); const auto [it, emplaced] = mCache.emplace( resourceName, packedResource->MakeSubBuffer(index.mOffset + ResourceIndex::sFilenameLength + 4, resourceSize)); mLogger.Spam() << "Resource: " << resourceName << " hash: " << std::hex << index.mHashKey << std::dec << " offset: " << index.mOffset << " size: " << resourceSize << "\n"; } } FileBuffer* PackedFileDataProvider::GetDataBuffer(const std::string& fileName) { mLogger.Spam() << "Searching for file: " << fileName << std::endl; if (mCache.contains(fileName)) { return &mCache.at(fileName); } return nullptr; } }
1,924
C++
.cpp
45
36.711111
109
0.679336
xavieran/BaKGL
39
2
32
GPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,379
characterTest.cpp
xavieran_BaKGL/bak/test/characterTest.cpp
#include "gtest/gtest.h" #include "bak/character.hpp" #include "bak/inventory.hpp" #include "bak/inventoryItem.hpp" namespace BAK { struct CharacterTestFixture : public ::testing::Test { CharacterTestFixture() : mObjects{} { mObjects.emplace_back(GameObject{ .mName = "Normal", .mImageSize = 1 }); mObjects.emplace_back(GameObject{ .mName = "Sword", .mImageSize = 2, .mType = ItemType::Sword}); mObjects.emplace_back(GameObject{ .mName = "Armor", .mImageSize = 4, .mType = ItemType::Armor, }); mObjects.emplace_back(GameObject{ .mName = "Stack", .mFlags = 0x0800, .mImageSize = 1, .mStackSize = mStackSize, .mDefaultStackSize = 5 }); } auto GetObject(const std::string& object) { return std::find_if(mObjects.begin(), mObjects.end(), [&object](const auto& elem){ return elem.mName == object; }); } InventoryItem MakeItem(const std::string& item, auto condition) { auto it = GetObject(item); ASSERT(it != mObjects.end()); return InventoryItem{ &(*it), ItemIndex{ static_cast<std::uint8_t>( std::distance(mObjects.begin(), it))}, static_cast<std::uint8_t>(condition), 0, 0}; } protected: void SetUp() override { Logging::LogState::SetLevel(Logging::LogLevel::Debug); } static constexpr auto mStackSize = 10; std::vector<GameObject> mObjects; }; TEST(CharacterTest, CheckAndSetStatus) { { std::uint8_t status = 0; EXPECT_EQ(CheckItemStatus(status, ItemStatus::Equipped), false); status = 1 << static_cast<std::uint8_t>(ItemStatus::Equipped); EXPECT_EQ(CheckItemStatus(status, ItemStatus::Equipped), true); } { std::uint8_t status = 0; EXPECT_EQ(CheckItemStatus(status, ItemStatus::Equipped), false); status = SetItemStatus(status, ItemStatus::Equipped, true); ASSERT_EQ(CheckItemStatus(status, ItemStatus::Equipped), true); status = SetItemStatus(status, ItemStatus::Equipped, false); EXPECT_EQ(CheckItemStatus(status, ItemStatus::Equipped), false); } } } // namespace
2,446
C++
.cpp
78
22.935897
72
0.579686
xavieran/BaKGL
39
2
32
GPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,380
timeTest.cpp
xavieran_BaKGL/bak/test/timeTest.cpp
#include "gtest/gtest.h" #include "bak/time.hpp" #include "bak/condition.hpp" #include "bak/skills.hpp" #include "com/logger.hpp" namespace BAK { struct GameTimeTestFixture : public ::testing::Test { GameTimeTestFixture() : mSkills{{ Skill{55, 55, 55, 0, 0, false, false}, Skill{45, 45, 45, 0, 0, false, false}, Skill{ 4, 4, 4, 0, 0, false, false}, Skill{17, 17, 17, 0, 0, false, false}, Skill{80, 80, 80, 0, 0, false, false}, // Def Skill{80, 80, 80, 0, 0, false, false}, // Cro Skill{80, 80, 80, 0, 0, false, false}, // Mel Skill{ 0, 0, 0, 0, 0, false, false}, // Cast Skill{80, 80, 80, 0, 0, false, false}, // Assess Skill{80, 80, 80, 0, 0, false, false}, // Arm Skill{80, 80, 80, 0, 0, false, false}, // Wea Skill{80, 80, 80, 0, 0, false, false}, // Bard Skill{80, 80, 80, 0, 0, false, false}, // Haggle Skill{80, 80, 80, 0, 0, false, false}, // Lockpick Skill{80, 80, 80, 0, 0, false, false}, // Scout Skill{80, 80, 80, 0, 0, false, false}}, // Stealth 0 } , mConditions{ ConditionValue{0}, ConditionValue{0}, ConditionValue{0}, ConditionValue{0}, ConditionValue{0}, ConditionValue{0}, ConditionValue{0}} { } protected: void SetUp() override { //Logging::LogState::SetLevel(Logging::LogLevel::Fatal); Logging::LogState::SetLevel(Logging::LogLevel::Debug); } Skills mSkills; Conditions mConditions; }; TEST_F(GameTimeTestFixture, EffectOfConditionsWithTime_Sick) { mSkills.GetSkill(BAK::SkillType::Stamina).mTrueSkill = 10; mConditions.SetCondition(BAK::Condition::Sick, 10); EffectOfConditionsWithTime(mSkills, mConditions, 0, 0); EXPECT_EQ(mConditions.GetCondition(BAK::Condition::Sick), 11); EXPECT_EQ(mSkills.GetSkill(BAK::SkillType::Stamina).mTrueSkill, 9); } TEST_F(GameTimeTestFixture, EffectOfConditionsWithTime_Plagued) { mSkills.GetSkill(BAK::SkillType::Stamina).mTrueSkill = 10; mConditions.SetCondition(BAK::Condition::Plagued, 11); EffectOfConditionsWithTime(mSkills, mConditions, 0, 0); EXPECT_EQ(mConditions.GetCondition(BAK::Condition::Plagued), 12); EXPECT_EQ(mSkills.GetSkill(BAK::SkillType::Stamina).mTrueSkill, 8); } TEST_F(GameTimeTestFixture, EffectOfConditionsWithTime_Poisoned) { mSkills.GetSkill(BAK::SkillType::Stamina).mTrueSkill = 10; mConditions.SetCondition(BAK::Condition::Poisoned, 11); EffectOfConditionsWithTime(mSkills, mConditions, 0, 0); EXPECT_EQ(mConditions.GetCondition(BAK::Condition::Poisoned), 12); EXPECT_EQ(mSkills.GetSkill(BAK::SkillType::Stamina).mTrueSkill, 7); } TEST_F(GameTimeTestFixture, EffectOfConditionsWithTime_Healing) { mSkills.GetSkill(BAK::SkillType::Stamina).mTrueSkill = 10; mConditions.SetCondition(BAK::Condition::Healing, 10); EffectOfConditionsWithTime(mSkills, mConditions, 0, 0); EXPECT_EQ(mConditions.GetCondition(BAK::Condition::Healing), 7); EXPECT_EQ(mSkills.GetSkill(BAK::SkillType::Stamina).mTrueSkill, 11); } TEST_F(GameTimeTestFixture, EffectOfConditionsWithTime_Multiple) { mSkills.GetSkill(BAK::SkillType::Stamina).mTrueSkill = 10; mConditions.SetCondition(BAK::Condition::Sick, 10); mConditions.SetCondition(BAK::Condition::Plagued, 10); mConditions.SetCondition(BAK::Condition::Poisoned, 10); mConditions.SetCondition(BAK::Condition::Healing, 10); EffectOfConditionsWithTime(mSkills, mConditions, 0, 0); mConditions.SetCondition(BAK::Condition::Sick, 9); mConditions.SetCondition(BAK::Condition::Plagued, 8); mConditions.SetCondition(BAK::Condition::Poisoned, 7); EXPECT_EQ(mConditions.GetCondition(BAK::Condition::Healing), 7); EXPECT_EQ(mSkills.GetSkill(BAK::SkillType::Stamina).mTrueSkill, 5); } TEST_F(GameTimeTestFixture, EffectOfConditionsWithTime_MultipleInInn) { mSkills.GetSkill(BAK::SkillType::Stamina).mTrueSkill = 10; mConditions.SetCondition(BAK::Condition::Sick, 10); mConditions.SetCondition(BAK::Condition::Plagued, 10); mConditions.SetCondition(BAK::Condition::Poisoned, 10); mConditions.SetCondition(BAK::Condition::Healing, 10); EffectOfConditionsWithTime(mSkills, mConditions, 0x85, 0x64); mConditions.SetCondition(BAK::Condition::Sick, 6); mConditions.SetCondition(BAK::Condition::Plagued, 8); mConditions.SetCondition(BAK::Condition::Poisoned, 7); EXPECT_EQ(mConditions.GetCondition(BAK::Condition::Healing), 7); EXPECT_EQ(mSkills.GetSkill(BAK::SkillType::Stamina).mTrueSkill, 7); } TEST_F(GameTimeTestFixture, NearDeathHeal) { // Normal progression mConditions.SetCondition(BAK::Condition::NearDeath, 100); ImproveNearDeath(mSkills, mConditions); EXPECT_EQ(mConditions.GetCondition(BAK::Condition::NearDeath), 99); // With healing mConditions.SetCondition(BAK::Condition::NearDeath, 70); mConditions.SetCondition(BAK::Condition::Healing, 1); ImproveNearDeath(mSkills, mConditions); EXPECT_EQ(mConditions.GetCondition(BAK::Condition::NearDeath), 62); } }
5,260
C++
.cpp
121
37.553719
72
0.692293
xavieran/BaKGL
39
2
32
GPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,381
partyTest.cpp
xavieran_BaKGL/bak/test/partyTest.cpp
#include "gtest/gtest.h" namespace { TEST(PartyTest, Positive) { EXPECT_EQ(2, 2); } } // namespace
106
C++
.cpp
7
13.285714
25
0.705263
xavieran/BaKGL
39
2
32
GPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,382
lockTest.cpp
xavieran_BaKGL/bak/test/lockTest.cpp
#include "gtest/gtest.h" #include "bak/lock.hpp" #include "bak/inventoryItem.hpp" #include "com/logger.hpp" namespace BAK { struct LockTestFixture : public ::testing::Test { LockTestFixture() : mKeyObject{ .mName = "Key", .mType = ItemType::Key } { } InventoryItem MakeKey(unsigned item) { return InventoryItem{ &mKeyObject, ItemIndex{item}, 1, 0, 0}; } protected: void SetUp() override { Logging::LogState::SetLevel(Logging::LogLevel::Debug); } GameObject mKeyObject; }; TEST_F(LockTestFixture, TryOpenLockWithKey) { auto key = MakeKey(62); EXPECT_EQ(TryOpenLockWithKey(key, 90), true); } TEST(FairyChest, ParseData) { const auto data = std::string{ R"(DAY NIGHT # DRV SAGHO OAB FIRMT FLC HRUNI EPY NGHSK # The light one breaks but never falls. His brother falls but never breaks.)"}; const auto fairyChest = GenerateFairyChest(data); EXPECT_EQ(fairyChest.mAnswer, "DAY NIGHT"); ASSERT_EQ(fairyChest.mOptions.size(), 4); EXPECT_EQ(fairyChest.mOptions[0], "DRV SAGHO"); EXPECT_EQ(fairyChest.mOptions[1], "OAB FIRMT"); EXPECT_EQ(fairyChest.mOptions[2], "FLC HRUNI"); EXPECT_EQ(fairyChest.mOptions[3], "EPY NGHSK"); EXPECT_EQ(fairyChest.mHint, "\nThe light one breaks but never falls.\nHis brother falls but never breaks."); } }
1,441
C++
.cpp
58
20.155172
112
0.661326
xavieran/BaKGL
39
2
32
GPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,383
templeTest.cpp
xavieran_BaKGL/bak/test/templeTest.cpp
#include "gtest/gtest.h" #include "bak/objectInfo.hpp" #include "bak/inventoryItem.hpp" #include "bak/temple.hpp" #include "com/logger.hpp" namespace BAK { struct TempleTestFixture : public ::testing::Test { TempleTestFixture() : mObjects{} { mObjects.emplace_back(GameObject{ "Staff", 1, 1, 1, 5, -5, 12, 10, 4, 4, 0, 0, 0, 0, RacialModifier::None, 0, ItemType::Other, 0, 0, 0, 0, 0, 0, 0, 0} ); mObjects.emplace_back(GameObject{ "Sword", 1008, 1, 10000, 71, 0, 49, 10, 28, 2, 0, 0, 0, 0, RacialModifier::Human, 0, ItemType::Sword, 0, 0, 0, 0, 0, 3, 3, 50} ); mObjects.emplace_back(GameObject{ "Armor", 1, 1, 5000, 1, 1, 1, 1, 0, 4, 0, 0, 0, 0, RacialModifier::None, 0, ItemType::Armor, 0, 0, 0, 0, 0, 0, 0, 0} ); } auto GetObject(const std::string& object) { return std::find_if(mObjects.begin(), mObjects.end(), [&object](const auto& elem){ return elem.mName == object; }); } InventoryItem MakeItem(const std::string& item, auto condition) { auto it = GetObject(item); ASSERT(it != mObjects.end()); return InventoryItem{ &(*it), ItemIndex{ static_cast<std::uint8_t>( std::distance(mObjects.begin(), it))}, static_cast<std::uint8_t>(condition), 0, 0}; } protected: void SetUp() override { Logging::LogState::SetLevel(Logging::LogLevel::Debug); } static constexpr auto mStackSize = 10; std::vector<GameObject> mObjects; }; TEST_F(TempleTestFixture, CanBless) { EXPECT_EQ(Temple::CanBlessItem(MakeItem("Staff", 1)), false); EXPECT_EQ(Temple::CanBlessItem(MakeItem("Sword", 1)), true); EXPECT_EQ(Temple::CanBlessItem(MakeItem("Armor", 1)), true); } TEST_F(TempleTestFixture, IsBlessed) { auto item = MakeItem("Sword", 1); EXPECT_EQ(Temple::IsBlessed(item), false); item.SetModifier(Modifier::Blessing1); EXPECT_EQ(Temple::IsBlessed(item), true); item.UnsetModifier(Modifier::Blessing1); EXPECT_EQ(Temple::IsBlessed(item), false); } TEST_F(TempleTestFixture, BlessItem) { const auto shopStats = ShopStats{ 0, 25, 75, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; auto item = MakeItem("Sword", 1); EXPECT_EQ(Temple::IsBlessed(item), false); Temple::BlessItem(item, shopStats); EXPECT_EQ(item.HasModifier(Modifier::Blessing3), true); Temple::RemoveBlessing(item); EXPECT_EQ(item.HasModifier(Modifier::Blessing3), false); } TEST_F(TempleTestFixture, CalculateBlessPrice) { const auto shopStats = ShopStats{ 0, 25, 75, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; EXPECT_EQ( Temple::CalculateBlessPrice(MakeItem("Sword", 1), shopStats), Royals{7750}); } TEST_F(TempleTestFixture, CalculateCureCost) { auto conditions = Conditions{}; auto skills = Skills{}; conditions.IncreaseCondition(BAK::Condition::NearDeath, 100); EXPECT_EQ( Temple::CalculateCureCost(65, false, skills, conditions, {}), Royals{1956}); } }
3,465
C++
.cpp
120
21.416667
69
0.566667
xavieran/BaKGL
39
2
32
GPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,384
skillTest.cpp
xavieran_BaKGL/bak/test/skillTest.cpp
#include "gtest/gtest.h" #include "bak/condition.hpp" #include "bak/skills.hpp" #include "com/logger.hpp" namespace BAK { struct SkillTestFixture : public ::testing::Test { SkillTestFixture() : mSkills{{ Skill{55, 55, 55, 0, 0, false, false}, Skill{45, 45, 45, 0, 0, false, false}, Skill{ 4, 4, 4, 0, 0, false, false}, Skill{17, 17, 17, 0, 0, false, false}, Skill{80, 80, 80, 0, 0, false, false}, // Def Skill{80, 80, 80, 0, 0, false, false}, // Cro Skill{80, 80, 80, 0, 0, false, false}, // Mel Skill{ 0, 0, 0, 0, 0, false, false}, // Cast Skill{80, 80, 80, 0, 0, false, false}, // Assess Skill{80, 80, 80, 0, 0, false, false}, // Arm Skill{80, 80, 80, 0, 0, false, false}, // Wea Skill{80, 80, 80, 0, 0, false, false}, // Bard Skill{80, 80, 80, 0, 0, false, false}, // Haggle Skill{80, 80, 80, 0, 0, false, false}, // Lockpick Skill{80, 80, 80, 0, 0, false, false}, // Scout Skill{80, 80, 80, 0, 0, false, false}}, // Stealth 0 } , mConditions{ ConditionValue{0}, ConditionValue{0}, ConditionValue{0}, ConditionValue{0}, ConditionValue{0}, ConditionValue{0}, ConditionValue{0}} , mSkillAffectors{} { } protected: void SetUp() override { //Logging::LogState::SetLevel(Logging::LogLevel::Fatal); Logging::LogState::SetLevel(Logging::LogLevel::Debug); } Skills mSkills; Conditions mConditions; std::vector<SkillAffector> mSkillAffectors; }; TEST_F(SkillTestFixture, CalculateEffectiveSkillValueTest) { auto skillValues = std::vector<unsigned>{}; for (unsigned i = 0; i < 16; i++) { skillValues.emplace_back( CalculateEffectiveSkillValue( static_cast<BAK::SkillType>(i), mSkills, mConditions, mSkillAffectors, SkillRead::Current)); } auto expectedSkillValues = std::vector<unsigned>{}; for (unsigned i = 0; i < 16; i++) expectedSkillValues.emplace_back(mSkills.GetSkill(static_cast<SkillType>(i)).mTrueSkill); EXPECT_EQ(skillValues, expectedSkillValues); } TEST_F(SkillTestFixture, WithSkillAffectorTest) { mSkillAffectors.emplace_back(SkillAffector{ 0x200, SkillType::Strength, 10, Time{}, Time{}}); mSkillAffectors.emplace_back(SkillAffector{ 0x100, SkillType::Melee, 25, Time{}, Time{}}); mSkillAffectors.emplace_back(SkillAffector{ 0x400, SkillType::Speed, 25, Time{}, Time{}}); auto skillValues = std::vector<unsigned>{}; for (unsigned i = 0; i < 16; i++) { skillValues.emplace_back( CalculateEffectiveSkillValue( static_cast<BAK::SkillType>(i), mSkills, mConditions, mSkillAffectors, SkillRead::Current)); } auto expectedSkillValues = std::vector<unsigned>{}; for (unsigned i = 0; i < 16; i++) expectedSkillValues.emplace_back(mSkills.GetSkill(static_cast<SkillType>(i)).mTrueSkill); expectedSkillValues[static_cast<std::size_t>(SkillType::Strength)] = 27; expectedSkillValues[static_cast<std::size_t>(SkillType::Melee)] = 105; expectedSkillValues[static_cast<std::size_t>(SkillType::Speed)] = 5; EXPECT_EQ(skillValues, expectedSkillValues); } TEST_F(SkillTestFixture, ConditionNonDrunkTest) { mConditions.IncreaseCondition(BAK::Condition::Sick, 50); mConditions.IncreaseCondition(BAK::Condition::Plagued, 50); mConditions.IncreaseCondition(BAK::Condition::Poisoned, 50); mConditions.IncreaseCondition(BAK::Condition::Starving, 50); mConditions.IncreaseCondition(BAK::Condition::NearDeath, 50); auto skillValues = std::vector<unsigned>{}; for (unsigned i = 0; i < 16; i++) { skillValues.emplace_back( CalculateEffectiveSkillValue( static_cast<BAK::SkillType>(i), mSkills, mConditions, mSkillAffectors, SkillRead::Current)); } // Sickness doesn't affect stats... auto expectedSkillValues = std::vector<unsigned>{}; for (unsigned i = 0; i < 16; i++) expectedSkillValues.emplace_back(mSkills.GetSkill(static_cast<SkillType>(i)).mTrueSkill); EXPECT_EQ(skillValues, expectedSkillValues); } TEST_F(SkillTestFixture, ConditionDrunkTest) { mConditions.IncreaseCondition(BAK::Condition::Drunk, 50); auto skillValues = std::vector<unsigned>{}; for (unsigned i = 0; i < 16; i++) { skillValues.emplace_back( CalculateEffectiveSkillValue( static_cast<BAK::SkillType>(i), mSkills, mConditions, mSkillAffectors, SkillRead::Current)); } auto expectedSkillValues = std::vector<unsigned>{ 55, 31, 4, 17}; for (unsigned i = 4; i < 16; i++) expectedSkillValues.emplace_back(56); expectedSkillValues[static_cast<unsigned>(BAK::SkillType::Casting)] = 0; EXPECT_EQ(skillValues, expectedSkillValues); } TEST_F(SkillTestFixture, ConditionDrunkWithSkillAffectorTest) { mSkillAffectors.emplace_back(SkillAffector{ 0x200, SkillType::Strength, 10, Time{}, Time{}}); mSkillAffectors.emplace_back(SkillAffector{ 0x100, SkillType::Melee, 25, Time{}, Time{}}); mSkillAffectors.emplace_back(SkillAffector{ 0x400, SkillType::Speed, 25, Time{}, Time{}}); mConditions.IncreaseCondition(BAK::Condition::Drunk, 50); auto skillValues = std::vector<unsigned>{}; for (unsigned i = 0; i < 16; i++) { skillValues.emplace_back( CalculateEffectiveSkillValue( static_cast<BAK::SkillType>(i), mSkills, mConditions, mSkillAffectors, SkillRead::Current)); } // Drunkenness doesn't affect speed or strength auto expectedSkillValues = std::vector<unsigned>{ 55, 31, 5, 27}; for (unsigned i = 4; i < 16; i++) expectedSkillValues.emplace_back(56); expectedSkillValues[static_cast<unsigned>(BAK::SkillType::Casting)] = 0; expectedSkillValues[static_cast<std::size_t>(SkillType::Melee)] = 74; EXPECT_EQ(skillValues, expectedSkillValues); } TEST_F(SkillTestFixture, ConditionHealingTest) { mConditions.IncreaseCondition(BAK::Condition::Healing, 50); auto skillValues = std::vector<unsigned>{}; for (unsigned i = 0; i < 16; i++) { skillValues.emplace_back( CalculateEffectiveSkillValue( static_cast<BAK::SkillType>(i), mSkills, mConditions, mSkillAffectors, SkillRead::Current)); } auto expectedSkillValues = std::vector<unsigned>{}; for (unsigned i = 0; i < 16; i++) expectedSkillValues.emplace_back(mSkills.GetSkill(static_cast<SkillType>(i)).mTrueSkill); EXPECT_EQ(skillValues, expectedSkillValues); } TEST_F(SkillTestFixture, LowHealthTest) { mSkills.GetSkill(BAK::SkillType::Stamina).mCurrent = 0; mSkills.GetSkill(BAK::SkillType::Stamina).mTrueSkill = 0; mSkills.GetSkill(BAK::SkillType::Health).mCurrent = 32; mSkills.GetSkill(BAK::SkillType::Health).mTrueSkill = 32; auto skillValues = std::vector<unsigned>{}; for (unsigned i = 0; i < 16; i++) { skillValues.emplace_back( CalculateEffectiveSkillValue( static_cast<BAK::SkillType>(i), mSkills, mConditions, mSkillAffectors, SkillRead::Current)); } auto expectedSkillValues = std::vector<unsigned>{ 32, 0, 3, 10}; for (unsigned i = 4; i < 9; i++) expectedSkillValues.emplace_back(47); for (unsigned i = 9; i < 16; i++) expectedSkillValues.emplace_back(63); expectedSkillValues[static_cast<unsigned>(BAK::SkillType::Casting)] = 0; EXPECT_EQ(skillValues, expectedSkillValues); } TEST_F(SkillTestFixture, LowHealthAndDrunkAndModifierTest) { mSkills.GetSkill(BAK::SkillType::Stamina).mCurrent = 0; mSkills.GetSkill(BAK::SkillType::Stamina).mTrueSkill = 0; mSkills.GetSkill(BAK::SkillType::Health).mCurrent = 32; mSkills.GetSkill(BAK::SkillType::Health).mTrueSkill = 32; mConditions.IncreaseCondition(BAK::Condition::Drunk, 50); mSkills.GetSkill(BAK::SkillType::Lockpick).mModifier += 15; auto skillValues = std::vector<unsigned>{}; for (unsigned i = 0; i < 16; i++) { skillValues.emplace_back( CalculateEffectiveSkillValue( static_cast<BAK::SkillType>(i), mSkills, mConditions, mSkillAffectors, SkillRead::Current)); } auto expectedSkillValues = std::vector<unsigned>{ 32, 0, 3, 10}; for (unsigned i = 4; i < 9; i++) expectedSkillValues.emplace_back(33); for (unsigned i = 9; i < 16; i++) expectedSkillValues.emplace_back(44); // actually 52 but, close enough for my liking... expectedSkillValues[static_cast<unsigned>(BAK::SkillType::Lockpick)] = 53; expectedSkillValues[static_cast<unsigned>(BAK::SkillType::Casting)] = 0; EXPECT_EQ(skillValues, expectedSkillValues); } TEST_F(SkillTestFixture, ImproveSkillTest) { auto& skill = mSkills.GetSkill(BAK::SkillType::Lockpick); skill.mMax = 24; skill.mCurrent = 24; skill.mTrueSkill = 24; for (unsigned i = 0; i < 3; i++) mSkills.ImproveSkill( mConditions, BAK::SkillType::Lockpick, BAK::SkillChange::ExercisedSkill, 2); EXPECT_EQ(skill.mTrueSkill, 24); EXPECT_EQ(skill.mExperience, 0xf0); EXPECT_EQ(skill.mUnseenImprovement, false); mSkills.ToggleSkill(BAK::SkillType::Lockpick); mSkills.ImproveSkill( mConditions, BAK::SkillType::Lockpick, BAK::SkillChange::ExercisedSkill, 2); EXPECT_EQ(skill.mTrueSkill, 25); EXPECT_EQ(skill.mExperience, 104); EXPECT_EQ(skill.mUnseenImprovement, true); } TEST_F(SkillTestFixture, ImproveSkillFromDialogTest) { auto& skill = mSkills.GetSkill(BAK::SkillType::Lockpick); skill.mMax = 24; skill.mCurrent = 24; skill.mTrueSkill = 24; mSkills.ToggleSkill(BAK::SkillType::Lockpick); mSkills.ImproveSkill( mConditions, BAK::SkillType::Lockpick, BAK::SkillChange::Direct, 5 << 8); EXPECT_EQ(skill.mTrueSkill, 31); EXPECT_EQ(skill.mExperience, 128); EXPECT_EQ(skill.mUnseenImprovement, true); } TEST_F(SkillTestFixture, DoAdjustHealth_FullHeal) { mSkills.SetSkill(BAK::SkillType::Health, Skill{0x28, 1, 1, 0, 0, false, false}); mSkills.SetSkill(BAK::SkillType::Stamina, Skill{0x2d, 0, 0, 0, 0, false, false}); EXPECT_EQ(mSkills.GetSkill(SkillType::Stamina).mTrueSkill, 0); EXPECT_EQ(mSkills.GetSkill(SkillType::Health).mTrueSkill, 1); DoAdjustHealth(mSkills, mConditions, 100, 0x7fff); EXPECT_EQ(mSkills.GetSkill(SkillType::Health).mTrueSkill, 0x28); EXPECT_EQ(mSkills.GetSkill(SkillType::Stamina).mTrueSkill, 0x2d); } TEST_F(SkillTestFixture, DoAdjustHealth_FullHealWithNearDeath) { mConditions.IncreaseCondition(BAK::Condition::NearDeath, 100); mSkills.SetSkill(BAK::SkillType::Health, Skill{0x28, 0x0, 0x0, 0, 0, false, false}); mSkills.SetSkill(BAK::SkillType::Stamina, Skill{0x2d, 0x0, 0x0, 0, 0, false, false}); EXPECT_EQ(mSkills.GetSkill(SkillType::Health).mTrueSkill, 0); EXPECT_EQ(mSkills.GetSkill(SkillType::Stamina).mTrueSkill, 0); DoAdjustHealth(mSkills, mConditions, 100, 0x7fff); EXPECT_EQ(mSkills.GetSkill(SkillType::Health).mTrueSkill, 0x1); EXPECT_EQ(mSkills.GetSkill(SkillType::Stamina).mTrueSkill, 0); } TEST_F(SkillTestFixture, DoAdjustHealth_ReduceHealth) { mSkills.SetSkill(BAK::SkillType::Health, Skill{0x28, 0x28, 0x28, 0, 0, false, false}); mSkills.SetSkill(BAK::SkillType::Stamina, Skill{0x2d, 0x28, 0x28, 0, 0, false, false}); EXPECT_EQ(mSkills.GetSkill(SkillType::Stamina).mTrueSkill, 0x28); EXPECT_EQ(mSkills.GetSkill(SkillType::Health).mTrueSkill, 0x28); // Percentage is irrelevant when reducing health... DoAdjustHealth(mSkills, mConditions, 0, -1 * (0x2d << 8)); EXPECT_EQ(mSkills.GetSkill(SkillType::Health).mTrueSkill, 0x23); EXPECT_EQ(mSkills.GetSkill(SkillType::Stamina).mTrueSkill, 0); } TEST_F(SkillTestFixture, DoAdjustHealth_ReduceHealthToNearDeath) { mSkills.SetSkill(BAK::SkillType::Health, Skill{0x28, 0x28, 0x28, 0, 0, false, false}); mSkills.SetSkill(BAK::SkillType::Stamina, Skill{0x2d, 0x28, 0x28, 0, 0, false, false}); EXPECT_EQ(mSkills.GetSkill(SkillType::Stamina).mTrueSkill, 0x28); EXPECT_EQ(mSkills.GetSkill(SkillType::Health).mTrueSkill, 0x28); // Percentage is irrelevant when reducing health... DoAdjustHealth(mSkills, mConditions, 0, -1 * (0xff << 8)); EXPECT_EQ(mSkills.GetSkill(SkillType::Health).mTrueSkill, 0x0); EXPECT_EQ(mSkills.GetSkill(SkillType::Stamina).mTrueSkill, 0x0); EXPECT_EQ(mConditions.GetCondition(Condition::NearDeath).Get(), 100); } }
13,641
C++
.cpp
353
31.031161
97
0.640033
xavieran/BaKGL
39
2
32
GPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,385
inventoryTest.cpp
xavieran_BaKGL/bak/test/inventoryTest.cpp
#include "gtest/gtest.h" #include "bak/inventory.hpp" #include "bak/inventoryItem.hpp" #include "com/logger.hpp" namespace BAK { struct InventoryTestFixture : public ::testing::Test { InventoryTestFixture() : mObjects{} { mObjects.emplace_back(GameObject{ .mName = "Normal", .mImageSize = 1, .mType = ItemType::Other }); mObjects.emplace_back(GameObject{ .mName = "Sword", .mImageSize = 2, .mType = ItemType::Sword, }); mObjects.emplace_back(GameObject{ .mName = "Armor", .mImageSize = 4, .mType = ItemType::Armor, }); mObjects.emplace_back(GameObject{ .mName = "Stack", .mFlags = 0x0800, .mImageSize = 1, .mStackSize = mStackSize, .mDefaultStackSize = 5, .mType = ItemType::Other }); } auto GetObject(const std::string& object) { return std::find_if(mObjects.begin(), mObjects.end(), [&object](const auto& elem){ return elem.mName == object; }); } InventoryItem MakeItem(const std::string& item, auto condition) { auto it = GetObject(item); ASSERT(it != mObjects.end()); return InventoryItem{ &(*it), ItemIndex{ static_cast<std::uint8_t>( std::distance(mObjects.begin(), it))}, static_cast<std::uint8_t>(condition), 0, 0}; } protected: void SetUp() override { Logging::LogState::SetLevel(Logging::LogLevel::Debug); } static constexpr auto mStackSize = 10; std::vector<GameObject> mObjects; }; TEST(InventoryTest, CheckAndSetStatus) { { std::uint8_t status = 0; EXPECT_EQ(CheckItemStatus(status, ItemStatus::Equipped), false); status = 1 << static_cast<std::uint8_t>(ItemStatus::Equipped); EXPECT_EQ(CheckItemStatus(status, ItemStatus::Equipped), true); } { std::uint8_t status = 0; EXPECT_EQ(CheckItemStatus(status, ItemStatus::Equipped), false); status = SetItemStatus(status, ItemStatus::Equipped, true); ASSERT_EQ(CheckItemStatus(status, ItemStatus::Equipped), true); status = SetItemStatus(status, ItemStatus::Equipped, false); EXPECT_EQ(CheckItemStatus(status, ItemStatus::Equipped), false); } } TEST_F(InventoryTestFixture, GetAndSetEquipped) { auto swordItem = MakeItem("Sword", 99); EXPECT_EQ(swordItem.IsEquipped(), false); swordItem.SetEquipped(true); EXPECT_EQ(swordItem.IsEquipped(), true); swordItem.SetEquipped(false); EXPECT_EQ(swordItem.IsEquipped(), false); } TEST_F(InventoryTestFixture, FindEquipped) { auto inventory = Inventory{24}; inventory.AddItem( MakeItem("Sword", 99)); auto it = inventory.FindEquipped(ItemType::Sword); EXPECT_EQ(it, inventory.GetItems().end()); } TEST_F(InventoryTestFixture, SpaceUsed) { auto inventory = Inventory{ 4, { MakeItem("Armor", 99), MakeItem("Normal", 10), MakeItem("Sword", 7), }}; EXPECT_EQ(inventory.GetSpaceUsed(), 4 + 1 + 2); } TEST_F(InventoryTestFixture, HasIncompleteStack) { { auto inventory = Inventory{ 5, { MakeItem("Armor", 99), MakeItem("Stack", 1), }}; EXPECT_EQ(inventory.HasIncompleteStack(MakeItem("Stack", 1)), true); } { auto inventory = Inventory{ 5, { MakeItem("Armor", 99), MakeItem("Stack", mStackSize), }}; EXPECT_EQ(inventory.HasIncompleteStack(MakeItem("Stack", 1)), false); } } TEST_F(InventoryTestFixture, FindStack) { { auto inventory = Inventory{ 5, { MakeItem("Stack", 10), MakeItem("Stack", 6), }}; const auto it = inventory.FindStack(MakeItem("Stack", 1)); ASSERT_NE(it, inventory.GetItems().end()); EXPECT_EQ(it->GetQuantity(), 6); } { auto inventory = Inventory{ 5, { MakeItem("Stack", 10) }}; const auto it = inventory.FindStack(MakeItem("Stack", 1)); ASSERT_NE(it, inventory.GetItems().end()); EXPECT_EQ(it->GetQuantity(), 10); } { auto inventory = Inventory{ 5, { MakeItem("Armor", 99), MakeItem("Stack", 10), MakeItem("Stack", 6), }}; const auto it = inventory.FindStack(MakeItem("Stack", 1)); ASSERT_NE(it, inventory.GetItems().end()); EXPECT_EQ(it->GetQuantity(), 6); } { auto inventory = Inventory{ 10, { MakeItem("Armor", 99), MakeItem("Stack", 10), MakeItem("Stack", 6), MakeItem("Stack", 10), MakeItem("Stack", 4), MakeItem("Stack", 6), MakeItem("Stack", 10), }}; const auto it = inventory.FindStack(MakeItem("Stack", 1)); ASSERT_NE(it, inventory.GetItems().end()); EXPECT_EQ(it->GetQuantity(), 4); } { auto inventory = Inventory{ 5, { MakeItem("Armor", 99), }}; const auto it = inventory.FindStack(MakeItem("Stack", 1)); EXPECT_EQ(it, inventory.GetItems().end()); } } TEST_F(InventoryTestFixture, CanAddCharacterSuccess) { auto inventory = Inventory{8}; auto armor = MakeItem("Armor", 99); auto sword = MakeItem("Sword", 99); auto stack = MakeItem("Stack", 5); EXPECT_EQ(inventory.CanAddCharacter(armor), 1); EXPECT_EQ(inventory.CanAddCharacter(sword), 1); EXPECT_EQ(inventory.CanAddCharacter(stack), 5); } TEST_F(InventoryTestFixture, CanAddCharacterPartial) { auto inventory = Inventory{ 5, { MakeItem("Armor", 99), MakeItem("Stack", 1), }}; EXPECT_EQ(inventory.GetSpaceUsed(), 4 + 1); EXPECT_EQ(inventory.CanAddCharacter(MakeItem("Normal", 1)), 0); EXPECT_EQ(inventory.CanAddCharacter(MakeItem("Sword", 1)), 0); EXPECT_EQ(inventory.CanAddCharacter(MakeItem("Armor", 1)), 0); auto stack5 = MakeItem("Stack", 5); auto stack10 = MakeItem("Stack", 10); EXPECT_EQ(inventory.CanAddCharacter(stack5), 5); EXPECT_EQ(inventory.CanAddCharacter(stack10), 9); } TEST_F(InventoryTestFixture, CanAddCharacterFail) { auto inventory = Inventory{ 5, { MakeItem("Armor", 99), MakeItem("Stack", 10), }}; EXPECT_EQ(inventory.GetSpaceUsed(), 4 + 1); EXPECT_EQ(inventory.CanAddCharacter(MakeItem("Normal", 1)), 0); EXPECT_EQ(inventory.CanAddCharacter(MakeItem("Sword", 1)), 0); EXPECT_EQ(inventory.CanAddCharacter(MakeItem("Armor", 1)), 0); auto stack5 = MakeItem("Stack", 5); auto stack10 = MakeItem("Stack", 10); EXPECT_EQ(inventory.CanAddCharacter(stack5), 0); EXPECT_EQ(inventory.CanAddCharacter(stack10), 0); } TEST_F(InventoryTestFixture, CanAddContainerFail) { auto inventory = Inventory{ 2, { MakeItem("Armor", 99), MakeItem("Stack", 10), }}; EXPECT_EQ(inventory.GetSpaceUsed(), 4 + 1); EXPECT_EQ(inventory.CanAddCharacter(MakeItem("Normal", 1)), 0); EXPECT_EQ(inventory.CanAddCharacter(MakeItem("Sword", 1)), 0); EXPECT_EQ(inventory.CanAddCharacter(MakeItem("Armor", 1)), 0); auto stack5 = MakeItem("Stack", 5); auto stack10 = MakeItem("Stack", 10); EXPECT_EQ(inventory.CanAddCharacter(stack5), 0); EXPECT_EQ(inventory.CanAddCharacter(stack10), 0); } TEST_F(InventoryTestFixture, AddItem) { auto inventory = Inventory{ 5, { }}; inventory.AddItem(MakeItem("Armor", 1)); ASSERT_EQ(inventory.GetNumberItems(), 1); { const auto& added = inventory.GetAtIndex(InventoryIndex{0}); EXPECT_EQ(added.GetCondition(), 1); } inventory.AddItem(MakeItem("Stack", mStackSize)); ASSERT_EQ(inventory.GetNumberItems(), 2); { const auto& added = inventory.GetAtIndex(InventoryIndex{1}); EXPECT_EQ(added.GetQuantity(), mStackSize); } inventory.AddItem(MakeItem("Stack", 4)); ASSERT_EQ(inventory.GetNumberItems(), 3); { const auto& added = inventory.GetAtIndex(InventoryIndex{2}); EXPECT_EQ(added.GetQuantity(), 4); } inventory.AddItem(MakeItem("Stack", 3)); ASSERT_EQ(inventory.GetNumberItems(), 3); { const auto& added = inventory.GetAtIndex(InventoryIndex{2}); EXPECT_EQ(added.GetQuantity(), 7); } inventory.AddItem(MakeItem("Stack", 6)); ASSERT_EQ(inventory.GetNumberItems(), 4); { const auto& existing = inventory.GetAtIndex(InventoryIndex{2}); EXPECT_EQ(existing.GetQuantity(), mStackSize); const auto& added = inventory.GetAtIndex(InventoryIndex{3}); EXPECT_EQ(added.GetQuantity(), 3); } inventory.AddItem(MakeItem("Stack", mStackSize)); ASSERT_EQ(inventory.GetNumberItems(), 5); { const auto& existing = inventory.GetAtIndex(InventoryIndex{3}); EXPECT_EQ(existing.GetQuantity(), mStackSize); const auto& added = inventory.GetAtIndex(InventoryIndex{4}); EXPECT_EQ(added.GetQuantity(), 3); } } TEST_F(InventoryTestFixture, RemoveItem) { { auto inventory = Inventory{ 5, { }}; inventory.AddItem(MakeItem("Armor", 1)); ASSERT_EQ(inventory.GetNumberItems(), 1); // This overload will just remove the first item that matches type inventory.RemoveItem(MakeItem("Armor", 5)); ASSERT_EQ(inventory.GetNumberItems(), 0); } { auto inventory = Inventory{ 5, { }}; inventory.AddItem(MakeItem("Armor", 1)); ASSERT_EQ(inventory.GetNumberItems(), 1); // This overload removes the matching index inventory.RemoveItem(InventoryIndex{0}); ASSERT_EQ(inventory.GetNumberItems(), 0); } { auto inventory = Inventory{ 5, { }}; inventory.AddItem(MakeItem("Stack", 10)); ASSERT_EQ(inventory.GetNumberItems(), 1); // This overload removes the matching index, even for stackables inventory.RemoveItem(InventoryIndex{0}); ASSERT_EQ(inventory.GetNumberItems(), 0); } { auto inventory = Inventory{ 5, { }}; inventory.AddItem(MakeItem("Stack", 10)); ASSERT_EQ(inventory.GetNumberItems(), 1); // Remove the whole stack inventory.RemoveItem(MakeItem("Stack", 10)); ASSERT_EQ(inventory.GetNumberItems(), 0); } { auto inventory = Inventory{ 5, { }}; inventory.AddItem(MakeItem("Stack", 10)); ASSERT_EQ(inventory.GetNumberItems(), 1); // Partially remove from the stack inventory.RemoveItem(MakeItem("Stack", 7)); ASSERT_EQ(inventory.GetNumberItems(), 1); EXPECT_EQ(inventory.GetAtIndex(InventoryIndex{0}).GetQuantity(), 3); } { auto inventory = Inventory{ 5, { }}; inventory.AddItem(MakeItem("Stack", 10)); inventory.AddItem(MakeItem("Stack", 6)); ASSERT_EQ(inventory.GetNumberItems(), 2); // Partially remove from the 1st stack and completely remove the 2nd inventory.RemoveItem(MakeItem("Stack", 8)); ASSERT_EQ(inventory.GetNumberItems(), 1); EXPECT_EQ(inventory.GetAtIndex(InventoryIndex{0}).GetQuantity(), 8); } } } // namespace
12,077
C++
.cpp
371
24.280323
77
0.587582
xavieran/BaKGL
39
2
32
GPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,386
keyContainerTest.cpp
xavieran_BaKGL/bak/test/keyContainerTest.cpp
#include "gtest/gtest.h" #include "bak/keyContainer.hpp" #include "bak/inventory.hpp" #include "bak/inventoryItem.hpp" #include "com/logger.hpp" namespace BAK { struct KeyTestFixture : public ::testing::Test { KeyTestFixture() : mObjects{} { mObjects.emplace_back(GameObject{ .mName = "Key1", .mType = ItemType::Key }); mObjects.emplace_back(GameObject{ .mName = "Key2", .mType = ItemType::Key }); mObjects.emplace_back(GameObject{ .mName = "NonKey", .mType = ItemType::Other }); } auto GetObject(const std::string& object) { return std::find_if(mObjects.begin(), mObjects.end(), [&object](const auto& elem){ return elem.mName == object; }); } InventoryItem MakeItem(const std::string& item, auto condition) { auto it = GetObject(item); ASSERT(it != mObjects.end()); return InventoryItem{ &(*it), ItemIndex{ static_cast<std::uint8_t>( std::distance(mObjects.begin(), it))}, static_cast<std::uint8_t>(condition), 0, 0}; } protected: void SetUp() override { Logging::LogState::SetLevel(Logging::LogLevel::Debug); } std::vector<GameObject> mObjects; }; TEST_F(KeyTestFixture, CanAddItem) { auto keys = KeyContainer{Inventory{8}}; EXPECT_EQ(keys.CanAddItem(MakeItem("Key1", 1)), true); EXPECT_EQ(keys.CanAddItem(MakeItem("NonKey", 1)), false); } TEST_F(KeyTestFixture, GiveItem) { auto keys = KeyContainer{Inventory{8}}; const auto item = MakeItem("Key1", 1); keys.GiveItem(item); { ASSERT_EQ(keys.GetInventory().GetNumberItems(), 1); EXPECT_EQ(keys.GetInventory().HaveItem(item), true); auto it = keys.GetInventory().FindItem(item); ASSERT_NE(it, keys.GetInventory().GetItems().end()); EXPECT_EQ(it->GetQuantity(), 1); } keys.GiveItem(item); { ASSERT_EQ(keys.GetInventory().GetNumberItems(), 1); auto it = keys.GetInventory().FindItem(item); ASSERT_NE(it, keys.GetInventory().GetItems().end()); EXPECT_EQ(it->GetQuantity(), 2); } const auto item2 = MakeItem("Key2", 1); keys.GiveItem(item2); { ASSERT_EQ(keys.GetInventory().GetNumberItems(), 2); EXPECT_EQ(keys.GetInventory().HaveItem(item2), true); auto it = keys.GetInventory().FindItem(item2); ASSERT_NE(it, keys.GetInventory().GetItems().end()); EXPECT_EQ(it->GetQuantity(), 1); } } TEST_F(KeyTestFixture, RemoveItem) { auto item1 = MakeItem("Key1", 1); auto item2 = MakeItem("Key2", 1); auto keys = KeyContainer{ Inventory{8, { MakeItem("Key1", 4), MakeItem("Key2", 1) }}}; keys.RemoveItem(item1); { ASSERT_EQ(keys.GetInventory().GetNumberItems(), 2); EXPECT_EQ(keys.GetInventory().HaveItem(item1), true); auto it = keys.GetInventory().FindItem(item1); ASSERT_NE(it, keys.GetInventory().GetItems().end()); EXPECT_EQ(it->GetQuantity(), 3); } keys.RemoveItem(item1); { ASSERT_EQ(keys.GetInventory().GetNumberItems(), 2); EXPECT_EQ(keys.GetInventory().HaveItem(item1), true); auto it = keys.GetInventory().FindItem(item1); ASSERT_NE(it, keys.GetInventory().GetItems().end()); EXPECT_EQ(it->GetQuantity(), 2); } keys.RemoveItem(item2); { ASSERT_EQ(keys.GetInventory().GetNumberItems(), 1); EXPECT_EQ(keys.GetInventory().HaveItem(item2), false); } } } // namespace
3,767
C++
.cpp
119
24.319328
67
0.593871
xavieran/BaKGL
39
2
32
GPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,387
customStateChoice.cpp
xavieran_BaKGL/bak/state/customStateChoice.cpp
#include "bak/state/customStateChoice.hpp" #include "bak/gameState.hpp" #include "bak/coordinates.hpp" namespace BAK::State { CustomStateEvaluator::CustomStateEvaluator(const GameState& gameState) : mGameState{gameState} {} bool CustomStateEvaluator::AnyCharacterStarving() const { bool foundStarving = false; mGameState.GetParty().ForEachActiveCharacter( [&](const auto& character){ if (character.GetConditions().GetCondition(Condition::Starving).Get() > 0) { foundStarving = true; return Loop::Finish; } return Loop::Continue; }); return foundStarving; } bool CustomStateEvaluator::Plagued() const { bool foundPlagued = false; mGameState.GetParty().ForEachActiveCharacter( [&](const auto& character){ if (character.GetConditions().GetCondition(Condition::Plagued).Get() > 0) { foundPlagued = true; return Loop::Finish; } return Loop::Continue; }); return foundPlagued; } bool CustomStateEvaluator::HaveSixSuitsOfArmor() const { unsigned armorCount = 0; mGameState.GetParty().ForEachActiveCharacter( [&](const auto& character){ const auto& items = character.GetInventory().GetItems(); for (const auto& item : items) { if (item.GetItemIndex() == sStandardArmor) { armorCount++; } } return Loop::Continue; }); return armorCount >= 6; } bool CustomStateEvaluator::AllPartyArmorIsGoodCondition() const { bool foundRepairableArmor = false; mGameState.GetParty().ForEachActiveCharacter( [&](const auto& character){ const auto& items = character.GetInventory().GetItems(); for (const auto& item : items) { if (item.IsItemType(ItemType::Armor) && item.IsRepairableByShop()) { foundRepairableArmor = true; return Loop::Finish; } } return Loop::Continue; }); return !foundRepairableArmor; } bool CustomStateEvaluator::PoisonedDelekhanArmyChests() const { unsigned foundPoisonedRations = 0; for (const auto& [zone, x, y] : { std::make_tuple(5u, 0x16b2fb, 0x111547), std::make_tuple(5u, 0x16b2fb, 0x110f20), std::make_tuple(5u, 0x16b33a, 0x11083c)}) { auto* container = mGameState.GetWorldContainer(ZoneNumber{zone}, GamePosition{x, y}); ASSERT(container); if (container->GetInventory().HaveItem(InventoryItemFactory::MakeItem(sPoisonedRations, 1))) { foundPoisonedRations++; } } return foundPoisonedRations == 3; } bool CustomStateEvaluator::AnyCharacterSansWeapon() const { bool noWeapon = false; mGameState.GetParty().ForEachActiveCharacter( [&](const auto& character){ if (character.HasEmptyStaffSlot() || character.HasEmptySwordSlot()) { noWeapon = true; return Loop::Finish; } return Loop::Continue; }); return !noWeapon; } bool CustomStateEvaluator::AnyCharacterHasNegativeCondition() const { bool nonZero = false; mGameState.GetParty().ForEachActiveCharacter([&](auto& character) { for (unsigned i = 0; i < 7; i++) { if (i == 4) continue; if (character.GetConditions().GetCondition(static_cast<Condition>(i)).Get() > 0) { nonZero = true; return Loop::Finish; } } return Loop::Continue; }); return nonZero; } bool CustomStateEvaluator::AnyCharacterIsUnhealthy() const { if (AnyCharacterHasNegativeCondition()) { return true; } bool nonZero = false; mGameState.GetParty().ForEachActiveCharacter([&](auto& character) { if (character.GetSkill(SkillType::TotalHealth) != character.GetMaxSkill(SkillType::TotalHealth)) { nonZero = true; return Loop::Finish; } return Loop::Continue; }); return nonZero; } bool CustomStateEvaluator::AllCharactersHaveNapthaMask() const { bool noMask = false; mGameState.GetParty().ForEachActiveCharacter([&](auto& character) { if (!character.GetInventory().HaveItem( InventoryItemFactory::MakeItem(sNapthaMask, 1))) { noMask = true; return Loop::Finish; } return Loop::Continue; }); return noMask; } bool CustomStateEvaluator::NormalFoodInArlieChest() const { auto* container = mGameState.GetWorldContainer(ZoneNumber{3}, GamePosition{1308000, 1002400}); ASSERT(container); return container->GetInventory().HaveItem(InventoryItemFactory::MakeItem(sRations, 1)); } bool CustomStateEvaluator::PoisonedFoodInArlieChest() const { auto* container = mGameState.GetWorldContainer(ZoneNumber{3}, GamePosition{1308000, 1002400}); ASSERT(container); return container->GetInventory().HaveItem(InventoryItemFactory::MakeItem(sPoisonedRations, 1)); } }
5,279
C++
.cpp
166
24.078313
104
0.626546
xavieran/BaKGL
39
2
32
GPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,388
event.cpp
xavieran_BaKGL/bak/state/event.cpp
#include "bak/state/event.hpp" #include "bak/state/offsets.hpp" #include "com/bits.hpp" #include "com/logger.hpp" namespace BAK::State { std::pair<unsigned, unsigned> CalculateComplexEventOffset(unsigned eventPtr) { const auto source = (eventPtr + 0x2540) & 0xffff; const auto byteOffset = source / 10; const auto bitOffset = source % 10 != 0 ? (source % 10) - 1 : 0; Logging::LogDebug(__FUNCTION__) << std::hex << " " << eventPtr << " source: " << source << " (" << byteOffset + sGameComplexEventRecordOffset << ", " << bitOffset << ")\n" << std::dec; return std::make_pair( byteOffset + sGameComplexEventRecordOffset, bitOffset); } std::pair<unsigned, unsigned> CalculateEventOffset(unsigned eventPtr) { const unsigned startOffset = sGameEventRecordOffset; const unsigned bitOffset = eventPtr & 0xf; const unsigned byteOffset = (0xfffe & (eventPtr >> 3)) + startOffset; Logging::LogSpam(__FUNCTION__) << std::hex << " " << eventPtr << " (" << byteOffset << ", " << bitOffset << ")\n" << std::dec; return std::make_pair(byteOffset, bitOffset); } void SetBitValueAt(FileBuffer& fb, unsigned byteOffset, unsigned bitOffset, unsigned value) { fb.Seek(byteOffset); const auto originalData = fb.GetUint16LE(); const auto data = SetBit(originalData, bitOffset, value != 0); fb.Seek(byteOffset); fb.PutUint16LE(data); Logging::LogSpam(__FUNCTION__) << std::hex << " " << byteOffset << " " << bitOffset << " original[" << +originalData << "] new[" << +data <<"]\n" << std::dec; } void SetEventFlag(FileBuffer& fb, unsigned eventPtr, unsigned value) { Logging::LogSpam(__FUNCTION__) << " " << std::hex << eventPtr << " to: " << value << std::dec << "\n"; if (eventPtr >= 0xdac0) { const auto [byteOffset, bitOffset] = CalculateComplexEventOffset(eventPtr); SetBitValueAt(fb, byteOffset, bitOffset, value); } else { const auto [byteOffset, bitOffset] = CalculateEventOffset(eventPtr); SetBitValueAt(fb, byteOffset, bitOffset, value); } } void SetEventFlagTrue (FileBuffer& fb, unsigned eventPtr) { SetEventFlag(fb, eventPtr, 1); } void SetEventFlagFalse(FileBuffer& fb, unsigned eventPtr) { SetEventFlag(fb, eventPtr, 0); } unsigned ReadBitValueAt(FileBuffer& fb, unsigned byteOffset, unsigned bitOffset) { fb.Seek(byteOffset); const unsigned eventData = fb.GetUint16LE(); const unsigned bitValue = eventData >> bitOffset; Logging::LogSpam(__FUNCTION__) << std::hex << " " << byteOffset << " " << bitOffset << " [" << +bitValue << "]\n" << std::dec; return bitValue; } unsigned ReadEvent(FileBuffer& fb, unsigned eventPtr) { if (eventPtr >= 0xdac0) { const auto [byteOffset, bitOffset] = CalculateComplexEventOffset(eventPtr); return ReadBitValueAt(fb, byteOffset, bitOffset); } else { const auto [byteOffset, bitOffset] = CalculateEventOffset(eventPtr); return ReadBitValueAt(fb, byteOffset, bitOffset); } } bool ReadEventBool(FileBuffer& fb, unsigned eventPtr) { return (ReadEvent(fb, eventPtr) & 0x1) == 1; } }
3,249
C++
.cpp
90
31.288889
99
0.653589
xavieran/BaKGL
39
2
32
GPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,389
lock.cpp
xavieran_BaKGL/bak/state/lock.cpp
#include "bak/state/lock.hpp" #include "bak/state/event.hpp" #include "bak/state/offsets.hpp" #include "bak/gameState.hpp" #include "com/logger.hpp" namespace BAK::State { void SetLockHasBeenSeen(FileBuffer& fb, unsigned lockIndex) { SetEventFlagTrue(fb, sLockHasBeenSeenFlag + lockIndex); } bool CheckLockHasBeenSeen(const GameState& gs, unsigned lockIndex) { return gs.ReadEventBool(sLockHasBeenSeenFlag + lockIndex); } }
439
C++
.cpp
15
27.266667
66
0.798561
xavieran/BaKGL
39
2
32
GPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,390
temple.cpp
xavieran_BaKGL/bak/state/temple.cpp
#include "bak/state/temple.hpp" #include "bak/state/event.hpp" #include "bak/gameState.hpp" namespace BAK::State { static constexpr auto sTempleSeenFlag = 0x1950; bool ReadTempleSeen(const GameState& gs, unsigned temple) { return gs.ReadEventBool(sTempleSeenFlag + temple); } void SetTempleSeen(FileBuffer& fb, unsigned temple) { SetEventFlagTrue(fb, sTempleSeenFlag + temple); } }
397
C++
.cpp
14
26.285714
57
0.792553
xavieran/BaKGL
39
2
32
GPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,391
dialog.cpp
xavieran_BaKGL/bak/state/dialog.cpp
#include "bak/state/dialog.hpp" #include "bak/state/event.hpp" #include "bak/state/offsets.hpp" #include "bak/gameState.hpp" #include "com/logger.hpp" namespace BAK::State { void SetEventDialogAction(FileBuffer& fb, const SetFlag& setFlag) { if (setFlag.mEventPointer >= 0xdac0 && setFlag.mEventPointer % 10 == 0) { const auto offset = std::get<0>(CalculateComplexEventOffset(setFlag.mEventPointer)); fb.Seek(offset); const auto data = fb.GetUint8(); const auto newData = ((data & setFlag.mEventMask) | setFlag.mEventData) ^ setFlag.mAlwaysZero; fb.Seek(offset); Logging::LogSpam(__FUNCTION__) << std::hex << " " << setFlag << " offset: " << offset << " data[" << +data << "] new[" << +newData <<"]\n" << std::dec; fb.PutUint8(newData); } else { if (setFlag.mEventPointer != 0) SetEventFlag(fb, setFlag.mEventPointer, setFlag.mEventValue); // TREAT THIS AS UINT16_T !!! EVENT MASK + EVENT DATA if (setFlag.mEventMask != 0) SetEventFlag(fb, setFlag.mEventMask, setFlag.mEventValue); if (setFlag.mAlwaysZero != 0) SetEventFlag(fb, setFlag.mAlwaysZero, setFlag.mEventValue); } } bool ReadConversationItemClicked(const GameState& gs, unsigned eventPtr) { return gs.ReadEventBool(sConversationChoiceMarkedFlag + eventPtr); } void SetConversationItemClicked(FileBuffer& fb, unsigned eventPtr) { return SetEventFlagTrue(fb, sConversationChoiceMarkedFlag + eventPtr); } bool CheckConversationOptionInhibited(const GameState& gs, unsigned eventPtr) { return gs.ReadEventBool(sConversationOptionInhibitedFlag + eventPtr); } }
1,747
C++
.cpp
47
31.255319
92
0.673578
xavieran/BaKGL
39
2
32
GPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,392
money.cpp
xavieran_BaKGL/bak/state/money.cpp
#include "bak/state/money.hpp" #include "bak/gameState.hpp" #include "bak/shop.hpp" #include "bak/state/event.hpp" #include "bak/types.hpp" #include "com/logger.hpp" namespace BAK::State { constexpr std::uint32_t CalculateMoneyOffset(Chapter chapter) { return 0x12f7 + ((chapter.mValue - 1) << 2) + 0x64; } void WritePartyMoney( FileBuffer& fb, Chapter chapter, Royals money) { fb.Seek(CalculateMoneyOffset(chapter)); fb.PutUint32LE(money.mValue); } Royals ReadPartyMoney( FileBuffer& fb, Chapter chapter) { fb.Seek(CalculateMoneyOffset(chapter)); return Royals{fb.GetUint32LE()}; } bool IsRomneyGuildWars(const GameState& gs, const ShopStats& shop) { const auto dc29 = gs.Apply(ReadEvent, 0xdc29); const auto dc2a = gs.Apply(ReadEvent, 0xdc2a); if (shop.mTempleNumber == 2 && gs.GetZone() == ZoneNumber{3}) { if (!(dc29 & 0x1)) { return false; } else { if (dc2a & 0x1) { return false; } return true; } } return false; } }
1,120
C++
.cpp
48
18.229167
66
0.630292
xavieran/BaKGL
39
2
32
GPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,393
encounter.cpp
xavieran_BaKGL/bak/state/encounter.cpp
#include "bak/state/encounter.hpp" #include "bak/state/event.hpp" #include "bak/state/offsets.hpp" #include "bak/gameState.hpp" #include "com/logger.hpp" namespace BAK::State { // Called by checkBlockTriggered, checkTownTriggered, checkBackgroundTriggered, checkZoneTriggered, // doEnableEncounter, doDialogEncounter, doDisableEncounter, doSoundEncounter bool CheckEncounterActive( const GameState& gs, const Encounter::Encounter& encounter, ZoneNumber zone) { const auto encounterIndex = encounter.GetIndex().mValue; const bool alreadyEncountered = CheckUniqueEncounterStateFlag( gs, zone, encounter.GetTileIndex(), encounterIndex); const bool recentlyEncountered = CheckRecentlyEncountered(gs, encounterIndex); // event flag 1 - this flag must be set to encounter the event const bool eventFlag1 = encounter.mSaveAddress != 0 ? !gs.GetEventState(CreateChoice(encounter.mSaveAddress)) : false; // event flag 2 - this flag must _not_ be set to encounter this event const bool eventFlag2 = encounter.mSaveAddress2 != 0 ? gs.GetEventState(CreateChoice(encounter.mSaveAddress2)) : false; return !(alreadyEncountered || recentlyEncountered || eventFlag1 || eventFlag2); } bool CheckCombatActive( const GameState& gs, const Encounter::Encounter& encounter, ZoneNumber zone) { const auto encounterIndex = encounter.GetIndex().mValue; const bool alreadyEncountered = CheckUniqueEncounterStateFlag( gs, zone, encounter.GetTileIndex(), encounterIndex); assert(std::holds_alternative<Encounter::Combat>(encounter.GetEncounter())); const auto combatIndex = std::get<Encounter::Combat>(encounter.GetEncounter()).mCombatIndex; // If this flag is set then this combat hasn't been seen const bool encounterFlag1464 = CheckCombatEncounterStateFlag(gs, combatIndex); // event flag 1 - this flag must be set to encounter the event const bool eventFlag1 = encounter.mSaveAddress != 0 ? !gs.GetEventState(CreateChoice(encounter.mSaveAddress)) : false; // event flag 2 - this flag must _not_ be set to encounter this event const bool eventFlag2 = encounter.mSaveAddress2 != 0 ? gs.GetEventState(CreateChoice(encounter.mSaveAddress2)) : false; Logging::LogInfo(__FUNCTION__) << " alreadyEncountered: " << alreadyEncountered << " combatEncounterStateFlag: " << encounterFlag1464 << " eventFlag1: " << eventFlag1 << " eventFlag2: " << eventFlag2 << "\n"; return !(alreadyEncountered || encounterFlag1464 || eventFlag1 || eventFlag2); } void SetPostDialogEventFlags( FileBuffer& fb, const Encounter::Encounter& encounter, ZoneNumber zone) { const auto tileIndex = encounter.GetTileIndex(); const auto encounterIndex = encounter.GetIndex().mValue; if (encounter.mSaveAddress3 != 0) { SetEventFlagTrue(fb, encounter.mSaveAddress3); } // Unknown 3 flag is associated with events like the sleeping glade and // timirianya danger zone (effectively, always encounter this encounter) if (encounter.mUnknown3 == 0) { // Inhibit for this chapter if (encounter.mUnknown2 != 0) { SetEventFlagTrue( fb, CalculateUniqueEncounterStateFlagOffset( zone, tileIndex, encounterIndex)); } // Inhibit for this tile SetRecentlyEncountered(fb, encounterIndex); } } // Background and Town void SetPostGDSEventFlags( FileBuffer& fb, const Encounter::Encounter& encounter) { if (encounter.mSaveAddress3 != 0) SetEventFlagTrue(fb, encounter.mSaveAddress3); } // Used by Block, Disable, Enable, Sound, Zone void SetPostEnableOrDisableEventFlags( FileBuffer& fb, const Encounter::Encounter& encounter, ZoneNumber zone) { if (encounter.mSaveAddress3 != 0) { SetEventFlagTrue(fb, encounter.mSaveAddress3); } if (encounter.mUnknown2 != 0) { SetUniqueEncounterStateFlag( fb, zone, encounter.GetTileIndex(), encounter.GetIndex().mValue, true); } } // For each encounter in every zone there is a unique enabled/disabled flag. // This is reset every time a new chapter is loaded (I think); unsigned CalculateUniqueEncounterStateFlagOffset( ZoneNumber zone, std::uint8_t tileIndex, std::uint8_t encounterIndex) { constexpr auto encounterStateOffset = 0x190; constexpr auto maxEncountersPerTile = 0xa; const auto zoneOffset = (zone.mValue - 1) * encounterStateOffset; const auto tileOffset = tileIndex * maxEncountersPerTile; const auto offset = zoneOffset + tileOffset + encounterIndex; return offset + encounterStateOffset; } bool CheckUniqueEncounterStateFlag( const GameState& gs, ZoneNumber zone, std::uint8_t tileIndex, std::uint8_t encounterIndex) { return gs.ReadEventBool( CalculateUniqueEncounterStateFlagOffset( zone, tileIndex, encounterIndex)); } void SetUniqueEncounterStateFlag( FileBuffer& fb, ZoneNumber zone, std::uint8_t tileIndex, std::uint8_t encounterIndex, bool value) { SetEventFlag( fb, CalculateUniqueEncounterStateFlagOffset( zone, tileIndex, encounterIndex), value); } unsigned CalculateCombatEncounterScoutedStateFlag( std::uint8_t encounterIndex) { constexpr auto offset = 0x145a; return offset + encounterIndex; } unsigned CalculateCombatEncounterStateFlag( unsigned combatIndex) { constexpr auto combatEncounterFlag = 0x1464; return combatIndex + combatEncounterFlag; } bool CheckCombatEncounterStateFlag( const GameState& gs, unsigned combatIndex) { constexpr auto alwaysTriggeredIndex = 0x3e8; if (combatIndex >= alwaysTriggeredIndex) return true; else return gs.ReadEventBool( CalculateCombatEncounterStateFlag(combatIndex)); } void SetCombatEncounterState( FileBuffer& fb, unsigned combatIndex, bool state) { constexpr auto alwaysTriggeredIndex = 0x3e8; if (combatIndex >= alwaysTriggeredIndex) { return; } SetEventFlag(fb, CalculateCombatEncounterStateFlag(combatIndex), state); } void SetCombatEncounterScoutedState( FileBuffer& fb, std::uint8_t encounterIndex, bool state) { SetEventFlag(fb, CalculateCombatEncounterScoutedStateFlag(encounterIndex), state); } // 1450 is "recently encountered this encounter" // should be cleared when we move to a new tile // (or it will inhibit the events of the new tile) unsigned CalculateRecentEncounterStateFlag( std::uint8_t encounterIndex) { // Refer readEncounterEventState1450 in IDA // These get cleared when we load a new tile constexpr auto offset = 0x1450; return offset + encounterIndex; } bool CheckRecentlyEncountered(const GameState& gs, std::uint8_t encounterIndex) { return gs.ReadEventBool(CalculateRecentEncounterStateFlag(encounterIndex)); } void SetRecentlyEncountered(FileBuffer& fb, std::uint8_t encounterIndex) { SetEventFlagTrue( fb, CalculateRecentEncounterStateFlag( encounterIndex)); } void ClearTileRecentEncounters( FileBuffer& fb) { for (unsigned i = 0; i < 10; i++) { SetEventFlagFalse(fb, CalculateRecentEncounterStateFlag(i)); SetEventFlagFalse(fb, CalculateCombatEncounterScoutedStateFlag(i)); } } void SetPostCombatCombatSpecificFlags(GameState& gs, unsigned combatIndex) { switch (combatIndex) { case 74: return; // this runs dialog 1cfdf1 (nago combat flags) // and is handled externally in my code // These are the Eortis quest rusalki combats case 131: [[fallthrough]]; case 132: [[fallthrough]]; case 133: [[fallthrough]]; case 134: [[fallthrough]]; case 135: if (gs.ReadEventBool(0x14e7) && gs.ReadEventBool(0x14e8) && gs.ReadEventBool(0x14e9) && gs.ReadEventBool(0x14ea) && gs.ReadEventBool(0x14eb)) { gs.SetEventValue(0xdb1c, 1); } return; // The never-ending combats? case 235: [[fallthrough]]; case 245: [[fallthrough]]; case 291: [[fallthrough]]; case 293: [[fallthrough]]; case 335: [[fallthrough]]; case 337: [[fallthrough]]; case 338: [[fallthrough]]; case 375: [[fallthrough]]; case 410: [[fallthrough]]; case 429: [[fallthrough]]; case 430: // Zero State 0x190 UniqueEncounterStateFlag // Zero state 0x1450 Recently encountered encounter // Zero state 145a // Zero state 1464 // Zero combat clicked... break; case 610: [[fallthrough]]; case 613: [[fallthrough]]; case 615: [[fallthrough]]; case 618: [[fallthrough]]; case 619: [[fallthrough]]; case 621: if (gs.ReadEventBool(0x16c6) && gs.ReadEventBool(0x16c9) && gs.ReadEventBool(0x16cb) && gs.ReadEventBool(0x16ce) && gs.ReadEventBool(0x16cf) && gs.ReadEventBool(0x16d1)) { gs.SetEventValue(0x1d17, 1); } default:break; } } void ZeroCombatClicked(unsigned combatIndex) { auto offset = (combatIndex * 0xe) + 0x131f; } Time GetCombatClickedTime(FileBuffer& fb, unsigned combatIndex) { static constexpr auto offset = 0x4457 + 0x64; fb.Seek(offset + (combatIndex << 2)); return Time{fb.GetUint32LE()}; } void SetCombatClickedTime(FileBuffer& fb, unsigned combatIndex, Time time) { static constexpr auto offset = 0x4457 + 0x64; fb.Seek(offset + (combatIndex << 2)); fb.PutUint32LE(time.mTime); } }
10,211
C++
.cpp
310
26.451613
99
0.673966
xavieran/BaKGL
39
2
32
GPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,394
skill.cpp
xavieran_BaKGL/bak/state/skill.cpp
#include "bak/state/skill.hpp" #include "bak/state/event.hpp" #include "bak/state/offsets.hpp" namespace BAK::State { bool ReadSkillSelected(FileBuffer& fb, unsigned character, unsigned skill) { constexpr auto maxSkills = 0x11; return ReadEventBool( fb, sSkillSelectedEventFlag + (character * maxSkills) + skill); } bool ReadSkillUnseenImprovement(FileBuffer& fb, unsigned character, unsigned skill) { constexpr auto maxSkills = 0x11; return ReadEventBool( fb, sSkillImprovementEventFlag + (character * maxSkills) + skill); } std::uint8_t ReadSelectedSkillPool(FileBuffer& fb, unsigned character) { fb.Seek(sCharacterSelectedSkillPool + (1 << character)); return fb.GetUint8(); } void SetSelectedSkillPool(FileBuffer& fb, unsigned character, std::uint8_t value) { fb.Seek(sCharacterSelectedSkillPool + (1 << character)); return fb.PutUint8(value); } void ClearUnseenImprovements(FileBuffer& fb, unsigned character) { constexpr auto maxSkills = 0x11; for (unsigned i = 0; i < maxSkills; i++) { const auto flag = sSkillImprovementEventFlag + (character * maxSkills) + i; SetEventFlagFalse(fb, flag); } } }
1,282
C++
.cpp
45
23.533333
84
0.691117
xavieran/BaKGL
39
2
32
GPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,395
item.cpp
xavieran_BaKGL/bak/state/item.cpp
#include "bak/state/item.hpp" #include "bak/state/event.hpp" #include "bak/state/offsets.hpp" #include "bak/gameState.hpp" namespace BAK::State { static constexpr auto maxItems = 0x14; bool ReadItemHasBeenUsed(const GameState& gs, unsigned character, unsigned itemIndex) { return gs.ReadEventBool( sItemUsedForCharacterAtLeastOnce + ((character * maxItems) + itemIndex)); } void SetItemHasBeenUsed(FileBuffer& fb, unsigned character, unsigned itemIndex) { SetEventFlagTrue( fb, sItemUsedForCharacterAtLeastOnce + ((character * maxItems) + itemIndex)); } }
620
C++
.cpp
20
26.8
86
0.735245
xavieran/BaKGL
39
2
32
GPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,396
door.cpp
xavieran_BaKGL/bak/state/door.cpp
#include "bak/state/door.hpp" #include "bak/state/event.hpp" #include "bak/state/offsets.hpp" #include "bak/gameState.hpp" #include "com/logger.hpp" namespace BAK::State { bool GetDoorState(const GameState& gs, unsigned doorIndex) { return gs.ReadEventBool(sDoorFlag + doorIndex); } void SetDoorState(FileBuffer& fb, unsigned doorIndex, bool state) { SetEventFlag(fb, sDoorFlag + doorIndex, state); } }
418
C++
.cpp
15
25.866667
65
0.775253
xavieran/BaKGL
39
2
32
GPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,397
dialog.cpp
xavieran_BaKGL/bak/encounter/dialog.cpp
#include "bak/encounter/dialog.hpp" #include "com/assert.hpp" #include "com/logger.hpp" #include "bak/fileBufferFactory.hpp" namespace BAK::Encounter { std::ostream& operator<<(std::ostream& os, const Dialog& dialog) { os << "Dialog { " << std::hex << dialog.mDialog << std::dec << "}"; return os; } DialogFactory::DialogFactory() : mDialogs{} { Load(); } const Dialog& DialogFactory::Get(unsigned i) const { ASSERT(i < mDialogs.size()); return mDialogs[i]; } void DialogFactory::Load() { auto fb = FileBufferFactory::Get().CreateDataBuffer( sFilename); const auto count = fb.GetUint32LE(); for (unsigned i = 0; i < count; i++) { fb.Skip(3); const auto target = fb.GetUint32LE(); mDialogs.emplace_back(KeyTarget{target}); fb.Skip(2); } } }
833
C++
.cpp
35
20.142857
71
0.65019
xavieran/BaKGL
39
2
32
GPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,398
eventFlag.cpp
xavieran_BaKGL/bak/encounter/eventFlag.cpp
#include "bak/encounter/eventFlag.hpp" #include <ios> namespace BAK::Encounter { std::ostream& operator<<(std::ostream& os, const EventFlag& ef) { os << "EventFlag { " << std::hex << ef.mEventPointer << std::dec << " Chance: " << +ef.mPercentChance << "% Enable: [" << ef.mIsEnable<< "]}"; return os; } }
333
C++
.cpp
11
26.727273
68
0.606918
xavieran/BaKGL
39
2
32
GPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,399
encounter.cpp
xavieran_BaKGL/bak/encounter/encounter.cpp
#include "bak/encounter/encounter.hpp" #include "com/logger.hpp" #include "com/visit.hpp" #include "graphics/glm.hpp" #include <iostream> #include <string_view> #include <vector> namespace BAK::Encounter { std::string_view ToString(EncounterType t) { switch (t) { case EncounterType::Background: return "background"; case EncounterType::Combat: return "combat"; case EncounterType::Comment: return "comment"; case EncounterType::Dialog: return "dialog"; case EncounterType::Health: return "health"; case EncounterType::Sound: return "sound"; case EncounterType::Town: return "town"; case EncounterType::Trap: return "trap"; case EncounterType::Zone: return "zone"; case EncounterType::Disable: return "disable"; case EncounterType::Enable: return "enable"; case EncounterType::Block: return "block"; default: return "unknown"; } } std::string_view ToString(const EncounterT& encounter) { return std::visit( overloaded{ [](const GDSEntry&){ return "GDSEntry"; }, [](const Block&){ return "Block"; }, [](const Combat&){ return "Combat"; }, [](const Dialog&){ return "Dialog"; }, [](const EventFlag&){ return "EventFlag"; }, [](const Zone&){ return "Zone"; } }, encounter); } std::ostream& operator<<(std::ostream& os, EncounterType e) { return os << ToString(e); } std::ostream& operator<<(std::ostream& os, const EncounterT& encounter) { std::visit([&os](const auto& e){ os << e; }, encounter); return os; } std::ostream& operator<<(std::ostream& os, const Encounter& e) { os << "Encounter { index: " << e.mIndex << " dims: " << e.mDimensions << " worldLocation: " << e.mLocation << " TL: " << e.mTopLeft << " BR: " << e.mBottomRight << " tile: " << e.mTile << std::hex << " savePtr: (" << e.mSaveAddress << ", " << e.mSaveAddress2 << ", " << e.mSaveAddress3 << ") Unknown [" << +e.mUnknown0 << "," << +e.mUnknown1 << "," << +e.mUnknown2 << "," << +e.mUnknown3 << "]" << std::dec << "{" << e.mEncounter << "}}"; return os; } std::pair< glm::uvec2, glm::uvec2> CalculateLocationAndDims( glm::uvec2 tile, std::uint8_t l, std::uint8_t t, std::uint8_t r, std::uint8_t b) { // Reminder - BAK coordinates origin is at bottom left // and x and y grow positive const auto topLeft = MakeGamePositionFromTileAndCell( tile, glm::vec<2, std::uint8_t>{l, t}); const auto bottomRight = MakeGamePositionFromTileAndCell( tile, glm::vec<2, std::uint8_t>{r, b}); // Give them some thickness const auto left = topLeft.x; const auto top = topLeft.y; const auto right = bottomRight.x; const auto bottom = bottomRight.y; ASSERT(right >= left && top >= bottom); const auto width = right == left ? gCellSize : right - left; const auto height = top == bottom ? gCellSize : top - bottom; // This is just not quite right... // not sure if I am rendering items at the wrong place // or if this is incorrect. According to the assembly // this 800 offset shouldn't be required... const auto xOffset = gCellSize / 2; const auto yOffset = xOffset; const auto location = GamePosition{ left + (width / 2) - xOffset, bottom + (height / 2) - yOffset}; const auto dimensions = glm::uvec2{ width, height}; return std::make_pair(location, dimensions); } std::vector<Encounter> LoadEncounters( const EncounterFactory& ef, FileBuffer& fb, Chapter chapter, glm::uvec2 tile, unsigned tileIndex) { const auto& logger = Logging::LogState::GetLogger("LoadEncounter"); std::vector<Encounter> encounters{}; // Ideally load all encounters... each chapter can be part of the // encounter type and they can be filtered later constexpr auto encounterEntrySize = 0x13; constexpr auto maxEncounters = 0xa; // + 2 for the count of encounters fb.Seek((chapter.mValue - 1) * (encounterEntrySize * maxEncounters + 2)); unsigned numberOfEncounters = fb.GetUint16LE(); encounters.reserve(numberOfEncounters); logger.Debug() << "Loading encounters for chapter: " << chapter.mValue << " encounters: " << numberOfEncounters << "\n"; for (unsigned i = 0; i < numberOfEncounters; i++) { auto loc = fb.Tell(); auto encounterType = static_cast<EncounterType>(fb.GetUint16LE()); const unsigned left = fb.GetUint8(); const unsigned top = fb.GetUint8(); const unsigned right = fb.GetUint8(); const unsigned bottom = fb.GetUint8(); const auto topLeft = glm::uvec2{left, top}; const auto bottomRight = glm::uvec2{right, bottom}; const auto& [location, dimensions] = CalculateLocationAndDims( tile, left, top, right, bottom); const unsigned encounterTableIndex = fb.GetUint16LE(); // Don't know const auto unknown0 = fb.GetUint8(); const auto unknown1 = fb.GetUint8(); const auto unknown2 = fb.GetUint8(); const auto saveAddr = fb.GetUint16LE(); const unsigned saveAddr2 = fb.GetUint16LE(); const unsigned saveAddr3 = fb.GetUint16LE(); const auto unknown3 = fb.GetUint16LE(); logger.Debug() << "Loaded encounter: " << tile << " loc: " << location << " dims: " << dimensions << " @ 0x" << std::hex << loc << std::dec << " type: " << encounterType << " index: " << encounterTableIndex << " saveAddr: 0x" << std::hex << saveAddr << ", " << saveAddr2 << ", " << saveAddr3 << std::dec << "\n"; encounters.emplace_back( ef.MakeEncounter( encounterType, encounterTableIndex, tile), EncounterIndex{i}, topLeft, bottomRight, location, dimensions, tile, tileIndex, saveAddr, saveAddr2, saveAddr3, unknown0, unknown1, unknown2, unknown3); } return encounters; } EncounterT EncounterFactory::MakeEncounter( EncounterType eType, unsigned encounterIndex, glm::uvec2 tile) const { switch (eType) { case EncounterType::Background: return mBackgrounds.Get(encounterIndex, tile); case EncounterType::Combat: { auto combat = mCombats.Get(encounterIndex); const auto tilePos = tile * static_cast<unsigned>(64000); combat.mNorthRetreat.mPosition += tilePos; combat.mSouthRetreat.mPosition += tilePos; combat.mWestRetreat.mPosition += tilePos; combat.mEastRetreat.mPosition += tilePos; for (auto& combatant : combat.mCombatants) { combatant.mLocation.mPosition += tilePos; } return combat; } case EncounterType::Comment: throw std::runtime_error("Can't make COMMENT encounters"); case EncounterType::Dialog: return mDialogs.Get(encounterIndex); case EncounterType::Health: throw std::runtime_error("Can't make HEALTH encounters"); case EncounterType::Sound: throw std::runtime_error("Can't make SOUND encounters"); case EncounterType::Town: return mTowns.Get(encounterIndex, tile); case EncounterType::Trap: { auto combat = mTraps.Get(encounterIndex); const auto tilePos = tile * static_cast<unsigned>(64000); combat.mNorthRetreat.mPosition += tilePos; combat.mSouthRetreat.mPosition += tilePos; combat.mWestRetreat.mPosition += tilePos; combat.mEastRetreat.mPosition += tilePos; for (auto& combatant : combat.mCombatants) { combatant.mLocation.mPosition += tilePos; } return combat; } case EncounterType::Zone: return mZones.Get(encounterIndex); case EncounterType::Disable: return mDisables.Get(encounterIndex); case EncounterType::Enable: return mEnables.Get(encounterIndex); case EncounterType::Block: return mBlocks.Get(encounterIndex); default: throw std::runtime_error("Can't make UNKNOWN encounters"); } } EncounterStore::EncounterStore( const EncounterFactory& ef, FileBuffer& fb, glm::uvec2 tile, unsigned tileIndex) : mChapters{} { mChapters.reserve(10); for (unsigned chapter = 1; chapter < 11; chapter++) { mChapters.emplace_back( LoadEncounters( ef, fb, Chapter{chapter}, tile, tileIndex)); } } const std::vector<Encounter>& EncounterStore::GetEncounters(Chapter chapter) const { assert(chapter.mValue > 0 && chapter.mValue < 11); return mChapters[chapter.mValue - 1]; } }
9,192
C++
.cpp
262
27.614504
124
0.608974
xavieran/BaKGL
39
2
32
GPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,400
zone.cpp
xavieran_BaKGL/bak/encounter/zone.cpp
#include "bak/encounter/zone.hpp" #include "bak/encounter/encounter.hpp" #include "com/assert.hpp" #include "bak/fileBufferFactory.hpp" namespace BAK::Encounter { std::ostream& operator<<(std::ostream& os, const Zone& zone) { os << "Zone { " << zone.mTargetZone << " worldPosition: " << zone.mTargetLocation << " dialog: " << std::hex << zone.mDialog << std::dec << "}"; return os; } ZoneFactory::ZoneFactory() : mZones{} { Load(); } const Zone& ZoneFactory::Get(unsigned i) const { ASSERT(i < mZones.size()); return mZones[i]; } void ZoneFactory::Load() { auto fb = FileBufferFactory::Get().CreateDataBuffer( sFilename); const auto count = fb.GetUint32LE(); for (unsigned i = 0; i < count; i++) { fb.Skip(3); const auto zone = fb.GetUint8(); const auto tile = glm::vec<2, unsigned>{ fb.GetUint8(), fb.GetUint8()}; const auto cell = glm::vec<2, std::uint8_t>{ fb.GetUint8(), fb.GetUint8()}; const auto heading = static_cast<std::uint16_t>( fb.GetUint16LE() / 0xffu); const auto dialog = fb.GetUint32LE(); ASSERT(fb.GetUint32LE() == 0); ASSERT(fb.GetUint16LE() == 0); const auto loc = MakeGamePositionFromTileAndCell(tile, cell); mZones.emplace_back( Zone{ ZoneNumber{zone}, GamePositionAndHeading{loc, heading}, KeyTarget{dialog}}); Logging::LogDebug("ZoneFactory") << "ZoneTransition: " << i << " " << mZones.back() << "\n"; } } }
1,596
C++
.cpp
51
25.117647
100
0.593607
xavieran/BaKGL
39
2
32
GPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,401
combat.cpp
xavieran_BaKGL/bak/encounter/combat.cpp
#include "bak/encounter/combat.hpp" #include "com/ostream.hpp" namespace BAK::Encounter { std::ostream& operator<<(std::ostream& os, const CombatantData& comb) { os << "{ Monster: " << comb.mMonster << ", MoveType: " << comb.mMovementType << ", " << comb.mLocation << "}"; return os; } std::ostream& operator<<(std::ostream& os, const Combat& comb) { os << "Combat { #" << comb.mCombatIndex << " Entry: " << std::hex << comb.mEntryDialog << " Scout: " << comb.mScoutDialog << std::dec << " \nTrap: " << comb.mTrap << " \nNorth: " << comb.mNorthRetreat << " \nWest: " << comb.mWestRetreat << " \nSouth: " << comb.mSouthRetreat << " \nEast: " << comb.mEastRetreat << " unknown: " << comb.mUnknown << " isAmbush: " << comb.mIsAmbush << " \nCombatants: ["; for (const auto& combat : comb.mCombatants) { os << combat << ", "; } os << "]"; return os; } }
983
C++
.cpp
30
27.3
80
0.543249
xavieran/BaKGL
39
2
32
GPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,402
gdsEntry.cpp
xavieran_BaKGL/bak/encounter/gdsEntry.cpp
#include "bak/encounter/gdsEntry.hpp" namespace BAK::Encounter { std::ostream& operator<<(std::ostream& os, const GDSEntry& gds) { os << "GDSEntry { " << gds.mHotspot.ToString() << " Entry: " << std::hex << gds.mEntryDialog << " Exit: " << gds.mExitDialog << std::dec << " Exit: " << gds.mExitPosition << " Walk: [" << gds.mWalkToDest << "]}"; return os; } }
405
C++
.cpp
12
29
63
0.569231
xavieran/BaKGL
39
2
32
GPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,403
teleport.cpp
xavieran_BaKGL/bak/encounter/teleport.cpp
#include "bak/encounter/teleport.hpp" #include "com/assert.hpp" #include "com/logger.hpp" #include "com/ostream.hpp" #include "bak/fileBufferFactory.hpp" namespace BAK::Encounter { std::ostream& operator<<(std::ostream& os, const Teleport& tele) { os << "Teleport { " << tele.mTargetZone << " worldPosition: " << tele.mTargetLocation << " GDS: " << tele.mTargetGDSScene << "}"; return os; } TeleportFactory::TeleportFactory() : mTeleports{} { Load(); } const Teleport& TeleportFactory::Get(unsigned i) const { ASSERT(i < mTeleports.size()); return mTeleports[i]; } void TeleportFactory::Load() { auto fb = FileBufferFactory::Get().CreateDataBuffer( sFilename); unsigned i = 0; while (fb.GetBytesLeft() != 0) { const auto possibleZone = fb.GetUint8(); const auto tile = glm::vec<2, unsigned>{ fb.GetUint8(), fb.GetUint8()}; const auto offset = glm::vec<2, std::uint8_t>{ fb.GetUint8(), fb.GetUint8()}; const auto heading = static_cast<std::uint16_t>( fb.GetUint16LE() / 0xffu); const auto hotspotNum = static_cast<std::uint8_t>(fb.GetUint16LE()); const auto hotspotChar = MakeHotspotChar(static_cast<std::uint8_t>(fb.GetUint16LE())); std::optional<ZoneNumber> zone{}; if (possibleZone != 0xff) zone = ZoneNumber{possibleZone}; const auto loc = MakeGamePositionFromTileAndCell(tile, offset); std::optional<HotspotRef> hotspotRef{}; if (hotspotNum != 0) hotspotRef = HotspotRef{hotspotNum, hotspotChar}; mTeleports.emplace_back( zone, GamePositionAndHeading{loc, heading}, hotspotRef); Logging::LogDebug("TeleportFactory") << "TeleportTransition: " << i++ << " " << mTeleports.back() << "\n"; } } }
1,879
C++
.cpp
55
28.018182
114
0.632394
xavieran/BaKGL
39
2
32
GPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,404
block.cpp
xavieran_BaKGL/bak/encounter/block.cpp
#include "bak/encounter/block.hpp" #include "com/assert.hpp" #include "bak/fileBufferFactory.hpp" namespace BAK::Encounter { std::ostream& operator<<(std::ostream& os, const Block& block) { os << "Block { " << std::hex << block.mDialog << std::dec << "}"; return os; } BlockFactory::BlockFactory() : mBlocks{} { Load(); } const Block& BlockFactory::Get(unsigned i) const { ASSERT(i < mBlocks.size()); return mBlocks[i]; } void BlockFactory::Load() { auto fb = FileBufferFactory::Get().CreateDataBuffer( sFilename); const auto count = fb.GetUint32LE(); for (unsigned i = 0; i < count; i++) { fb.Skip(3); const auto target = fb.GetUint32LE(); ASSERT(fb.GetUint16LE() == 0); mBlocks.emplace_back(KeyTarget{target}); } } }
813
C++
.cpp
34
20.147059
69
0.641092
xavieran/BaKGL
39
2
32
GPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,405
audio.cpp
xavieran_BaKGL/audio/audio.cpp
#include "audio/audio.hpp" #include "bak/soundStore.hpp" #include "SDL_mixer.h" namespace AudioA { AudioManager::AudioManager() : mCurrentMusicTrack{nullptr}, mMusicStack{}, mSoundQueue{}, mSoundPlaying{}, mSoundData{}, mMusicData{}, mRunning{true}, mQueuePlayThread{[this]{ using namespace std::chrono_literals; while (mRunning) { if (!mSoundPlaying && !mSoundQueue.empty()) { std::this_thread::sleep_for(1ms); auto sound = Get().mSoundQueue.front(); Get().mSoundQueue.pop(); Get().PlaySoundImpl(sound); } std::this_thread::sleep_for(10ms); } }}, mLogger{Logging::LogState::GetLogger("AudioManager")} { if (SDL_Init(SDL_INIT_AUDIO) < 0) { mLogger.Error() << "Couldn't initialize SDL: " << SDL_GetError() << std::endl; } if (Mix_OpenAudio(sAudioRate, sAudioFormat, sAudioChannels, sAudioBuffers) < 0) { mLogger.Error() << "Couldn't initialize SDL: " << SDL_GetError() << std::endl; } Mix_VolumeMusic(sAudioVolume); //Mix_SetMidiPlayer(MIDI_ADLMIDI); Mix_SetMidiPlayer(MIDI_OPNMIDI); //Mix_SetMidiPlayer(MIDI_Fluidsynth); } AudioManager& AudioManager::Get() { static AudioManager audioManager{}; return audioManager; } void AudioManager::ChangeMusicTrack(MusicIndex musicI) { if (!mMusicStack.empty()) { mMusicStack.pop(); } auto* music = GetMusic(musicI); mMusicStack.push(music); mLogger.Debug() << "Changing track to: " << musicI << " stack size: " << mMusicStack.size() << "\n"; PlayTrack(music); } void AudioManager::PlayTrack(Mix_Music* music) { if (music == mCurrentMusicTrack) return; const auto startTime = Mix_GetMusicLoopStartTime(music); if (mCurrentMusicTrack && Mix_PlayingMusicStream(mCurrentMusicTrack)) { Mix_CrossFadeMusicStream(mCurrentMusicTrack, music, -1, sFadeOutTime, 0); } else { Mix_FadeInMusicStream(music, -1, sFadeOutTime); } mCurrentMusicTrack = music; } void AudioManager::PopTrack() { if (mMusicStack.empty()) { mLogger.Debug() << "Popping music track, stack already empty\n"; return; } if (mMusicStack.size() == 1) { mLogger.Debug() << "Popping music track, stack now empty\n"; auto* music = mMusicStack.top(); mMusicStack.pop(); mCurrentMusicTrack = nullptr; Mix_FadeOutMusicStream(music, sFadeOutTime); } else { mLogger.Debug() << "Popping music track, stack size: " << mMusicStack.size() << "\n"; mMusicStack.pop(); PlayTrack(mMusicStack.top()); } } void AudioManager::PlaySound(SoundIndex sound) { mLogger.Debug() << "Queueing sound: " << sound << "\n"; mSoundQueue.emplace(sound); } void AudioManager::PlaySoundImpl(SoundIndex sound) { mLogger.Debug() << "Playing sound: " << sound << "\n"; mSoundPlaying = true; std::visit(overloaded{ [](Mix_Music* music){ Mix_PlayMusicStream(music, 1); Mix_HookMusicStreamFinished(music, &AudioManager::RewindMusic, nullptr); }, [](Mix_Chunk* chunk){ }}, GetSound(sound)); } void AudioManager::RewindMusic(Mix_Music* music, void*) { // This seems to be necessary for some midi snippets that e.g. 61 DRAG // that stop playing back after they've been played once or twice... //Mix_RewindMusicStream(music); Mix_FreeMusic(music); auto& soundData = Get().mSoundData; soundData.erase( std::find_if( soundData.begin(), soundData.end(), [music](const auto& sound) { return std::holds_alternative<Mix_Music*>(sound.second) && std::get<Mix_Music*>(sound.second) == music; })); Get().mSoundPlaying = false; } void AudioManager::StopMusicTrack() { if (mCurrentMusicTrack) { Mix_FadeOutMusicStream(mCurrentMusicTrack, 2000); mCurrentMusicTrack = nullptr; } } Mix_Music* AudioManager::GetMusic(MusicIndex music) { if (!mMusicData.contains(music)) { auto& data = BAK::SoundStore::Get().GetSoundData(music.mValue); ASSERT(data.GetSounds().size() > 0); auto* fb = data.GetSounds()[0].GetSamples(); auto* rwops = SDL_RWFromMem(fb->GetCurrent(), fb->GetSize()); if (!rwops) { mLogger.Error() << SDL_GetError() << std::endl; } Mix_Music* musicData = Mix_LoadMUS_RW(rwops, 0); if (!musicData) { mLogger.Error() << Mix_GetError() << std::endl; } Mix_SetMusicTempo(musicData, sMusicTempo); mMusicData[music] = musicData; } return mMusicData[music]; } AudioManager::Sound AudioManager::GetSound(SoundIndex sound) { if (!mSoundData.contains(sound)) { auto& data = BAK::SoundStore::Get().GetSoundData(sound.mValue); ASSERT(data.GetSounds().size() > 0); auto* fb = data.GetSounds()[0].GetSamples(); auto* rwops = SDL_RWFromMem(fb->GetCurrent(), fb->GetSize()); if (!rwops) { mLogger.Error() << SDL_GetError() << std::endl; } Mix_Music* musicData = Mix_LoadMUS_RW(rwops, 0); if (!musicData) { mLogger.Error() << Mix_GetError() << std::endl; } Mix_SetMusicTempo(musicData, sMusicTempo); mSoundData[sound] = musicData; } return mSoundData[sound]; } void AudioManager::SwitchMidiPlayer(MidiPlayer midiPlayer) { ClearSounds(); switch (midiPlayer) { case MidiPlayer::ADLMIDI: Mix_SetMidiPlayer(MIDI_ADLMIDI); break; case MidiPlayer::OPNMIDI: Mix_SetMidiPlayer(MIDI_OPNMIDI); break; case MidiPlayer::FluidSynth: Mix_SetMidiPlayer(MIDI_Fluidsynth); break; default: throw std::runtime_error("Invalid midi player type"); } } void AudioManager::ClearSounds() { mCurrentMusicTrack = nullptr; for (auto& [_, music] : mMusicData) { Mix_HaltMusicStream(music); Mix_FreeMusic(music); } mMusicData.clear(); for (auto& [_, sound] : mSoundData) { std::visit(overloaded{ [](Mix_Music* music){ Mix_HaltMusicStream(music); Mix_FreeMusic(music); }, [](Mix_Chunk* chunk){ Mix_FreeChunk(chunk); }}, sound); } mSoundData.clear(); while (!mMusicStack.empty()) mMusicStack.pop(); mSoundPlaying = false; } AudioManager::~AudioManager() { ClearSounds(); mRunning = false; mQueuePlayThread.join(); Mix_CloseAudio(); SDL_Quit(); } }
6,909
C++
.cpp
238
22.315126
93
0.605438
xavieran/BaKGL
39
2
32
GPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,406
shaders.cpp
xavieran_BaKGL/shaders/shaders.cpp
#include "shaders/shaders.hpp" #include <array> #include <algorithm> namespace Shaders { static constexpr auto ShaderFiles = std::to_array<std::pair<const char*, const char*>>({ #include "shaders/shader_binary_cache.hxx" }); std::optional<std::string> GetFile(std::string shaderFile) { auto it = std::find_if(ShaderFiles.begin(), ShaderFiles.end(), [&shaderFile](const auto& shader) { return shaderFile == std::string(shader.first); }); if (it != ShaderFiles.end()) { return it->second; } return std::nullopt; } }
584
C++
.cpp
21
23.47619
88
0.658887
xavieran/BaKGL
39
2
32
GPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,407
compile_shaders.cpp
xavieran_BaKGL/shaders/compile_shaders.cpp
#include "com/logger.hpp" #include "graphics/shaderProgram.hpp" #include <GLFW/glfw3.h> void ErrorCallback(int code, const char* desc) { const auto& logger = Logging::LogState::GetLogger("GLFW"); logger.Error() << " Code: " << code << " desc: " << desc << std::endl; } int main(int argc, char** argv) { const auto& logger = Logging::LogState::GetLogger("main"); Logging::LogState::SetLevel(Logging::LogLevel::Debug); if (argc != 3) { logger.Error() << "Usage: compile_shaders vertex fragment"; return -1; } const auto vertexShaderPath = std::string{argv[1]}; const auto fragmentShaderPath = std::string{argv[2]}; auto program = ShaderProgram{vertexShaderPath, std::optional<std::string>{}, fragmentShaderPath}; logger.Info() << "Compiling " << vertexShaderPath << " and " << fragmentShaderPath << std::endl; glfwSetErrorCallback(ErrorCallback); if( !glfwInit() ) { logger.Error() << "Failed to open GLFW window" << std::endl; return -1; } GLFWwindow* window; glfwWindowHint(GLFW_SAMPLES, 4); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE); unsigned height = 600; unsigned width = 800; window = glfwCreateWindow( width, height, "BaK", NULL, NULL); if( window == NULL ) { logger.Error() << "Failed to open GLFW window" << std::endl; glfwTerminate(); return -1; } glfwMakeContextCurrent(window); // Initialize GLEW glewExperimental = true; // Needed for core profile if (glewInit() != GLEW_OK) { logger.Error() << "Failed to initialize GLEW" << std::endl; glfwTerminate(); return -1; } try { auto programID = program.Compile(); } catch (const std::exception& e) { logger.Error() << "Failed to compile shaders: " << e.what() << std::endl; return -1; } logger.Info() << "Successfully compiled shaders" << std::endl; return 0; }
2,172
C++
.cpp
63
28.761905
101
0.637019
xavieran/BaKGL
39
2
32
GPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,408
factory.cpp
xavieran_BaKGL/game/interactable/factory.cpp
#include "game/interactable/factory.hpp" namespace Game { std::string_view ToString(InteractableType it) { switch (it) { case InteractableType::Chest: return "Chest"; case InteractableType::RiftMachine: return "RiftMachine"; case InteractableType::Building: return "Building"; case InteractableType::Tombstone: return "Tombstone"; case InteractableType::Sign: return "Sign"; case InteractableType::Pit: return "Pit"; case InteractableType::Body: return "Body"; case InteractableType::DirtMound: return "DirtMound"; case InteractableType::Corn: return "Corn"; case InteractableType::Campfire: return "Campfire"; case InteractableType::Tunnel0: return "Tunnel0"; case InteractableType::Door: return "Door"; case InteractableType::CrystalTree: return "CrystalTree"; case InteractableType::Stones: return "Stones"; case InteractableType::FoodBush: return "FoodBush"; case InteractableType::PoisonBush: return "PoisonBush"; case InteractableType::HealthBush: return "HealthBush"; case InteractableType::Slab: return "Slab"; case InteractableType::Stump: return "Stump"; case InteractableType::Well: return "Well"; case InteractableType::SiegeEngine: return "SiegeEngine"; case InteractableType::Scarecrow: return "Scarecrow"; case InteractableType::DeadAnimal: return "DeadAnimal"; case InteractableType::Catapult: return "Catapult"; case InteractableType::Column: return "Column"; case InteractableType::Tunnel1: return "Tunnel1"; case InteractableType::Bag: return "Bag"; case InteractableType::Ladder: return "Ladder"; default: return "UnknownInteractable"; } } }
1,809
C++
.cpp
38
40.105263
65
0.701923
xavieran/BaKGL
39
2
32
GPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,409
show_scene.cpp
xavieran_BaKGL/app/show_scene.cpp
#include "bak/encounter/teleport.hpp" #include "bak/gameState.hpp" #include "com/algorithm.hpp" #include "com/logger.hpp" #include "com/visit.hpp" #include "graphics/glfw.hpp" #include "graphics/guiRenderer.hpp" #include "graphics/inputHandler.hpp" #include "graphics/texture.hpp" #include "gui/actors.hpp" #include "gui/backgrounds.hpp" #include "gui/guiManager.hpp" #include "gui/core/mouseEvent.hpp" #include "gui/window.hpp" #include "imgui/imguiWrapper.hpp" #include <GL/glew.h> #include <GLFW/glfw3.h> #include <functional> #include <memory> #include <sstream> struct DummyZoneLoader : public BAK::IZoneLoader { public: void DoTeleport(BAK::Encounter::Teleport i) override { Logging::LogDebug("DummyZoneLoader") << "Teleporting to: " << "\n"; } void LoadGame(std::string, std::optional<BAK::Chapter>) override { } }; #undef main int main(int argc, char** argv) { const auto& logger = Logging::LogState::GetLogger("main"); Logging::LogState::SetLevel(Logging::LogLevel::Debug); Logging::LogState::Disable("LoadScenes"); Logging::LogState::Disable("LoadSceneIndices"); Logging::LogState::Disable("DialogStore"); Logging::LogState::Disable("Gui::Actors"); auto guiScalar = 3.5f; auto nativeWidth = 320.0f; auto nativeHeight = 240.0f; auto width = nativeWidth * guiScalar; auto height = nativeHeight * guiScalar * 0.83f; auto window = Graphics::MakeGlfwWindow( height, width, "Show GUI"); //auto guiScale = glm::vec3{guiScalar, guiScalar, 0}; auto guiScaleInv = glm::vec2{1 / guiScalar, 1 / guiScalar}; glViewport(0, 0, width, height); ImguiWrapper::Initialise(window.get()); // Dark blue background glClearColor(0.0f, 0.0f, 0.0, 0.0f); auto spriteManager = Graphics::SpriteManager{}; auto guiRenderer = Graphics::GuiRenderer{ width, height, guiScalar, spriteManager}; const auto root = static_cast<std::uint8_t>(std::atoi(argv[1])); auto currentSceneRef = BAK::HotspotRef{root, *argv[2]}; auto gameState = std::invoke([&](){ if (argc >= 4) { auto* data = new BAK::GameData{argv[3]}; return BAK::GameState{data}; } else return BAK::GameState{}; }); const auto font = Gui::Font{"GAME.FNT", spriteManager}; const auto actors = Gui::Actors{spriteManager}; const auto backgrounds = Gui::Backgrounds{spriteManager}; Gui::Window rootWidget{ spriteManager, width / guiScalar, height / guiScalar}; auto guiManager = Gui::GuiManager{ rootWidget.GetCursor(), spriteManager, gameState }; DummyZoneLoader zoneLoader{}; guiManager.SetZoneLoader(&zoneLoader); rootWidget.AddChildFront(&guiManager); guiManager.EnterGDSScene(currentSceneRef, []{}); // Set up input callbacks Graphics::InputHandler inputHandler{}; Graphics::InputHandler::BindMouseToWindow(window.get(), inputHandler); Graphics::InputHandler::BindKeyboardToWindow(window.get(), inputHandler); inputHandler.BindMouse( GLFW_MOUSE_BUTTON_LEFT, [&](const auto click) { rootWidget.OnMouseEvent( Gui::LeftMousePress{guiScaleInv * click}); }, [&](const auto click) { rootWidget.OnMouseEvent( Gui::LeftMouseRelease{guiScaleInv * click}); } ); inputHandler.BindMouse( GLFW_MOUSE_BUTTON_RIGHT, [&](auto click) { rootWidget.OnMouseEvent( Gui::RightMousePress{guiScaleInv * click}); }, [&](auto click) { rootWidget.OnMouseEvent( Gui::RightMouseRelease{guiScaleInv * click}); } ); inputHandler.BindMouseMotion( [&](auto pos) { rootWidget.OnMouseEvent( Gui::MouseMove{guiScaleInv * pos}); } ); // Graphics stuff glfwSetInputMode(window.get(), GLFW_CURSOR, GLFW_CURSOR_HIDDEN); glEnable(GL_MULTISAMPLE); glDisable(GL_DEPTH_TEST); glDepthFunc(GL_LESS); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); do { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); guiRenderer.RenderGui(&rootWidget); glfwSwapBuffers(window.get()); glfwPollEvents(); } while (glfwGetKey(window.get(), GLFW_KEY_ESCAPE) != GLFW_PRESS && glfwWindowShouldClose(window.get()) == 0); ImguiWrapper::Shutdown(); delete gameState.GetGameData(); return 0; }
4,702
C++
.cpp
145
25.786207
77
0.646195
xavieran/BaKGL
39
2
32
GPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,410
display_ttm.cpp
xavieran_BaKGL/app/display_ttm.cpp
#include "bak/scene.hpp" #include "com/logger.hpp" #include "bak/file/fileBuffer.hpp" int main(int argc, char** argv) { const auto& logger = Logging::LogState::GetLogger("main"); Logging::LogState::SetLevel(Logging::LogLevel::Debug); if (argc < 3) { std::cerr << "No arguments provided!\nUsage: " << argv[0] << " ADS TTM\n"; return -1; } std::string adsFile{argv[1]}; std::string ttmFile{argv[2]}; logger.Info() << "Loading ADS and TTM:" << adsFile << " " << ttmFile << std::endl; { auto fb = BAK::FileBufferFactory::Get().CreateDataBuffer(adsFile); BAK::LoadSceneIndices(fb); } { auto fb = BAK::FileBufferFactory::Get().CreateDataBuffer(ttmFile); BAK::LoadScenes(fb); } return 0; }
809
C++
.cpp
26
25.269231
86
0.605982
xavieran/BaKGL
39
2
32
GPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,411
bmx_explorer.cpp
xavieran_BaKGL/app/bmx_explorer.cpp
#include "com/logger.hpp" #include "graphics/inputHandler.hpp" #include "graphics/glm.hpp" #include "graphics/glfw.hpp" #include "graphics/guiRenderer.hpp" #include "gui/icons.hpp" #include "gui/textBox.hpp" #include "gui/window.hpp" #include "imgui/imguiWrapper.hpp" #include <GLFW/glfw3.h> #include <glm/glm.hpp> #include <memory> #include <sstream> int main(int argc, char** argv) { const auto& logger = Logging::LogState::GetLogger("main"); Logging::LogState::SetLevel(Logging::LogLevel::Debug); auto guiScalar = 4.0f; auto width = 1600.0f; auto height = 1000.0f; auto window = Graphics::MakeGlfwWindow( height, width, "BMX Explorer"); glViewport(0, 0, width, height); // Dark blue background glClearColor(0.15f, 0.31f, 0.36f, 0.0f); auto spriteManager = Graphics::SpriteManager{}; auto guiRenderer = Graphics::GuiRenderer{ width, height, guiScalar, spriteManager}; auto fontManager = Gui::FontManager{spriteManager}; auto root = Gui::Window{ spriteManager, width / guiScalar, height / guiScalar}; auto bookTextures = Graphics::TextureStore{}; BAK::TextureFactory::AddToTextureStore( bookTextures, "BOOK.BMX", "BOOK.PAL"); auto bookSpriteSheet = spriteManager.AddSpriteSheet(); spriteManager.GetSpriteSheet(bookSpriteSheet).LoadTexturesGL(bookTextures); auto icons = Gui::Icons{spriteManager}; int iconI = 0; auto picture = Gui::Widget{ Gui::ImageTag{}, Graphics::SpriteSheetIndex{0}, Graphics::TextureIndex{0}, glm::vec2{50,50}, glm::vec2{100,100}, true}; //const auto& [ss, ti, dims] = icons.GetBookIcon(iconI); picture.SetSpriteSheet(bookSpriteSheet); picture.SetTexture(Graphics::TextureIndex{static_cast<unsigned>(iconI)}); picture.SetDimensions(bookTextures.GetTexture(static_cast<unsigned>(iconI)).GetDims()); root.AddChildBack(&picture); root.HideCursor(); const auto& font = fontManager.GetSpellFont(); std::vector<std::unique_ptr<Gui::Widget>> spellIcons{}; auto pos = glm::vec2{2, 100}; for (unsigned i = 0; i < 96; i++) { if (i == 24) { pos = glm::vec2{2, 120}; } spellIcons.emplace_back( std::make_unique<Gui::Widget>( Graphics::DrawMode::Sprite, font.GetSpriteSheet(), static_cast<Graphics::TextureIndex>( font.GetFont().GetIndex(i)), Graphics::ColorMode::Texture, glm::vec4{1.f, 0.f, 0.f, 1.f}, pos, glm::vec2{font.GetFont().GetWidth(i), font.GetFont().GetHeight()}, true )); pos += glm::vec2{font.GetFont().GetWidth(i) + 1, 0}; root.AddChildBack(spellIcons.back().get()); } Graphics::InputHandler inputHandler{}; inputHandler.Bind(GLFW_KEY_RIGHT, [&]{ iconI++; picture.SetSpriteSheet(bookSpriteSheet); picture.SetTexture(Graphics::TextureIndex{static_cast<unsigned>(iconI)}); picture.SetDimensions(bookTextures.GetTexture(static_cast<unsigned>(iconI)).GetDims()); logger.Debug() << "Pic: " << picture << "\n"; }); inputHandler.Bind(GLFW_KEY_LEFT, [&]{ iconI--; picture.SetSpriteSheet(bookSpriteSheet); picture.SetTexture(Graphics::TextureIndex{static_cast<unsigned>(iconI)}); picture.SetDimensions(bookTextures.GetTexture(static_cast<unsigned>(iconI)).GetDims()); logger.Debug() << "Pic: " << picture << "\n"; }); inputHandler.BindMouse(GLFW_MOUSE_BUTTON_LEFT, [&](auto p) { logger.Debug() << p << "\n"; iconI++; picture.SetSpriteSheet(bookSpriteSheet); picture.SetTexture(Graphics::TextureIndex{static_cast<unsigned>(iconI)}); picture.SetDimensions(bookTextures.GetTexture(static_cast<unsigned>(iconI)).GetDims() / 2); logger.Debug() << "ICONI: " << iconI << " Pic: " << picture << "\n"; }, [](auto){}); inputHandler.BindMouse(GLFW_MOUSE_BUTTON_RIGHT, [&](auto p){ iconI--; picture.SetSpriteSheet(bookSpriteSheet); picture.SetTexture(Graphics::TextureIndex{static_cast<unsigned>(iconI)}); picture.SetDimensions(bookTextures.GetTexture(static_cast<unsigned>(iconI)).GetDims() / 2); logger.Debug() << "ICONI: " << iconI << " Pic: " << picture << "\n"; }, [](auto){}); Graphics::InputHandler::BindMouseToWindow(window.get(), inputHandler); Graphics::InputHandler::BindKeyboardToWindow(window.get(), inputHandler); double currentTime = 0; double lastTime = 0; float deltaTime = 0; glfwSetCursorPos(window.get(), width / 2, height / 2); glEnable(GL_MULTISAMPLE); glDisable(GL_DEPTH_TEST); glDepthFunc(GL_LESS); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); double pointerPosX, pointerPosY; double acc = 0; unsigned i = 0; do { inputHandler.SetHandleInput(true); glfwPollEvents(); glfwGetCursorPos(window.get(), &pointerPosX, &pointerPosY); inputHandler.HandleInput(window.get()); // { *** Draw 2D GUI *** glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); guiRenderer.RenderGui(&root); glfwSwapBuffers(window.get()); } while (glfwGetKey(window.get(), GLFW_KEY_ESCAPE) != GLFW_PRESS && glfwWindowShouldClose(window.get()) == 0); glfwTerminate(); return 0; }
5,623
C++
.cpp
145
31.406897
99
0.635008
xavieran/BaKGL
39
2
32
GPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,412
display_save.cpp
xavieran_BaKGL/app/display_save.cpp
#include "bak/gameData.hpp" extern "C" { #include "com/getopt.h" } #include "com/string.hpp" #include "com/logger.hpp" struct Options { bool shops{}; std::array<bool, 13> zones{}; bool party{}; bool skill_affectors{}; bool time_state{}; bool combat_inventories{}; bool combat_grid{}; bool combat_world{}; bool combat_stats{}; bool combat_click{}; bool combat_lists{}; std::string saveFile{}; }; Options Parse(int argc, char** argv) { Options values{}; struct option options[] = { {"help", no_argument, 0, 'h'}, {"shop", no_argument, 0, 's'}, {"zone", required_argument, 0, 'z'}, {"party", required_argument, 0, 'p'}, {"skill_affectors", required_argument, 0, 'k'}, {"time_state", required_argument, 0, 't'}, {"combat_inventories", no_argument, 0, 'c'}, {"combat_grid", no_argument, 0, 'g'}, {"combat_world", no_argument, 0, 'w'}, {"combat_stats", no_argument, 0, 'S'}, {"combat_click", no_argument, 0, 'C'}, {"combat_lists", no_argument, 0, 'l'}, }; int optionIndex = 0; int opt; while ((opt = getopt_long(argc, argv, "hsz:pktcgwSCl", options, &optionIndex)) != -1) { if (opt == 'h') { exit(0); } else if (opt == 's') { values.shops = true; } else if (opt == 'z') { auto zones = SplitString(",", std::string{optarg}); for (auto z : zones) { values.zones[std::atoi(z.c_str())] = true; } } else if (opt == 'p') { values.party = true; } else if (opt == 'k') { values.skill_affectors = true; } else if (opt == 't') { values.time_state = true; } else if (opt == 'c') { values.combat_inventories = true; } else if (opt == 'g') { values.combat_grid = true; } else if (opt == 'w') { values.combat_world = true; } else if (opt == 'S') { values.combat_stats = true; } else if (opt == 'C') { values.combat_click = true; } else if (opt == 'l') { values.combat_lists = true; } } if (optind < argc) { values.saveFile = argv[optind]; } return values; } int main(int argc, char** argv) { const auto& logger = Logging::LogState::GetLogger("main"); Logging::LogState::SetLevel(Logging::LogLevel::Debug); Logging::LogState::SetLogTime(false); Logging::LogState::Disable("LoadSpells"); Logging::LogState::Disable("LoadSpellDoc"); Logging::LogState::Disable("Symbol"); Logging::LogState::Disable("CreateFileBuffer"); const auto options = Parse(argc, argv); logger.Info() << "Loading save:" << options.saveFile << std::endl; BAK::GameData gameData(options.saveFile); logger.Info() << "SaveName: " << gameData.mName << "\n"; logger.Info() << "Tile: " << std::hex << gameData.mLocation.mTile << std::dec << " " << gameData.mLocation.mTile << "\n"; logger.Info() << "MapLocation: " << gameData.mMapLocation << "\n"; logger.Info() << "Location: " << gameData.mLocation.mLocation << "\n"; logger.Info() << "Time: " << gameData.mTime; if (options.party) { auto party = gameData.LoadParty(); logger.Info() << "Party: " << party << "\n"; } if (options.skill_affectors) { for (unsigned i = 0; i < 6; i++) { logger.Info() << "SkillAffectors for character: " << i << " Affectors: " << gameData.GetCharacterSkillAffectors(BAK::CharIndex{i}) << "\n"; } } if (options.time_state) { logger.Info() << "TimeExpiringState: " << gameData.LoadTimeExpiringState() << "\n"; } for (unsigned i = 0; i < 13; i++) { if (options.zones[i]) { auto containers = gameData.LoadContainers(i); logger.Info() << "Containers(" << i << ")\n"; for (auto& con : containers) { logger.Info() << " " << con << "\n"; } } } if (options.shops) { logger.Info() << "Shops\n"; auto containers = gameData.LoadShops(); for (auto& con : containers) { logger.Info() << " " << con << "\n"; } } if (options.combat_inventories) { auto containers = gameData.LoadCombatInventories(); logger.Info() << "Combat Inventories\n"; for (auto& con : containers) { logger.Info() << " " << con << "\n"; } } if (options.combat_grid) { auto cgl = gameData.LoadCombatGridLocations(); logger.Info() << "Combat Grid Locations\n"; for (unsigned i = 0; i < cgl.size(); i++) { logger.Info() << " #" << i << " " << cgl[i] << "\n"; } } if (options.combat_world) { logger.Info() << "CombatWorldLocations: \n"; auto cwl = gameData.LoadCombatWorldLocations(); for (unsigned i = 0; i < cwl.size(); i++) { logger.Info() << " #" << i << " " << cwl[i] << "\n"; } } if (options.combat_lists) { logger.Info() << "CombatEntityLists: \n"; auto cel = gameData.LoadCombatEntityLists(); for (unsigned i = 0; i < cel.size(); i++) { logger.Info() << " #" << i << " " << cel[i] << "\n"; } } return 0; }
5,725
C++
.cpp
194
21.680412
126
0.497182
xavieran/BaKGL
39
2
32
GPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,413
play_book.cpp
xavieran_BaKGL/app/play_book.cpp
#include "bak/gameState.hpp" #include "com/algorithm.hpp" #include "com/logger.hpp" #include "com/visit.hpp" #include "graphics/glfw.hpp" #include "graphics/guiRenderer.hpp" #include "graphics/inputHandler.hpp" #include "graphics/texture.hpp" #include "gui/actors.hpp" #include "gui/animatorStore.hpp" #include "gui/backgrounds.hpp" #include "gui/bookPlayer.hpp" #include "gui/core/mouseEvent.hpp" #include "gui/window.hpp" #include "imgui/imguiWrapper.hpp" #include <GL/glew.h> #include <GLFW/glfw3.h> #include <functional> #include <memory> #include <sstream> // SDL... #undef main int main(int argc, char** argv) { const auto& logger = Logging::LogState::GetLogger("main"); Logging::LogState::SetLevel(Logging::LogLevel::Debug); Logging::LogState::Disable("LoadScenes"); Logging::LogState::Disable("LoadSceneIndices"); Logging::LogState::Disable("DialogStore"); Logging::LogState::Disable("Gui::Actors"); Logging::LogState::Disable("CreateFileBuffer"); auto guiScalar = 3.5f; auto nativeWidth = 320.0f; auto nativeHeight = 200.0f; auto width = nativeWidth * guiScalar; auto height = nativeHeight * guiScalar; auto window = Graphics::MakeGlfwWindow( height, width, "Show GUI"); //auto guiScale = glm::vec3{guiScalar, guiScalar, 0}; auto guiScaleInv = glm::vec2{1 / guiScalar, 1 / guiScalar}; glViewport(0, 0, width, height); ImguiWrapper::Initialise(window.get()); // Dark blue background glClearColor(0.0f, 0.0f, 0.0, 0.0f); auto spriteManager = Graphics::SpriteManager{}; auto guiRenderer = Graphics::GuiRenderer{ width, height, guiScalar, spriteManager}; if (argc < 2) { std::cerr << "Usage: " << argv[0] << " BASENAME\n"; return -1; } std::string bookFile{argv[1]}; const auto font = Gui::Font{"BOOK.FNT", spriteManager}; const auto backgrounds = Gui::Backgrounds{spriteManager}; Gui::Window rootWidget{ spriteManager, width / guiScalar, height / guiScalar}; Gui::AnimatorStore animatorStore{}; auto bookPlayer = Gui::BookPlayer{ spriteManager, font, backgrounds, [](){} }; bookPlayer.PlayBook(bookFile); rootWidget.AddChildBack(bookPlayer.GetBackground()); // Set up input callbacks Graphics::InputHandler inputHandler{}; Graphics::InputHandler::BindMouseToWindow(window.get(), inputHandler); Graphics::InputHandler::BindKeyboardToWindow(window.get(), inputHandler); inputHandler.BindMouse( GLFW_MOUSE_BUTTON_LEFT, [&](const auto click) { rootWidget.OnMouseEvent( Gui::LeftMousePress{guiScaleInv * click}); bookPlayer.AdvancePage(); }, [&](const auto click) { rootWidget.OnMouseEvent( Gui::LeftMouseRelease{guiScaleInv * click}); } ); inputHandler.BindMouse( GLFW_MOUSE_BUTTON_RIGHT, [&](auto click) { rootWidget.OnMouseEvent( Gui::RightMousePress{guiScaleInv * click}); }, [&](auto click) { rootWidget.OnMouseEvent( Gui::RightMouseRelease{guiScaleInv * click}); } ); inputHandler.BindMouseMotion( [&](auto pos) { rootWidget.OnMouseEvent( Gui::MouseMove{guiScaleInv * pos}); } ); // Graphics stuff glfwSetInputMode(window.get(), GLFW_CURSOR, GLFW_CURSOR_HIDDEN); glEnable(GL_MULTISAMPLE); glDisable(GL_DEPTH_TEST); glDepthFunc(GL_LESS); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); double currentTime = 0; double lastTime = 0; do { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); currentTime = glfwGetTime(); animatorStore.OnTimeDelta(currentTime - lastTime); lastTime = currentTime; guiRenderer.RenderGui(&rootWidget); glfwSwapBuffers(window.get()); glfwPollEvents(); } while (glfwGetKey(window.get(), GLFW_KEY_ESCAPE) != GLFW_PRESS && glfwWindowShouldClose(window.get()) == 0); ImguiWrapper::Shutdown(); return 0; }
4,344
C++
.cpp
136
25.139706
77
0.642306
xavieran/BaKGL
39
2
32
GPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,414
display_fmap.cpp
xavieran_BaKGL/app/display_fmap.cpp
#include "bak/fmap.hpp" #include "bak/file/packedResourceFile.hpp" #include "com/logger.hpp" int main(int argc, char** argv) { Logging::LogState::SetLevel(Logging::LogLevel::Debug); Logging::LogState::Disable("LoadZoneRef"); BAK::FMapXY(); BAK::FMapTowns(); return 0; }
294
C++
.cpp
11
23.545455
58
0.706093
xavieran/BaKGL
39
2
32
GPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,415
main3d.cpp
xavieran_BaKGL/app/main3d.cpp
#include "bak/backgroundSounds.hpp" #include "bak/camera.hpp" #include "bak/constants.hpp" #include "bak/container.hpp" #include "bak/coordinates.hpp" #include "bak/gameData.hpp" #include "bak/screens.hpp" #include "bak/state/encounter.hpp" extern "C" { #include "com/getopt.h" } #include "com/logger.hpp" #include "com/path.hpp" #include "com/visit.hpp" #include "game/console.hpp" #include "game/gameRunner.hpp" #include "game/systems.hpp" #include "graphics/inputHandler.hpp" #include "graphics/guiRenderer.hpp" #include "graphics/glfw.hpp" #include "graphics/framebuffer.hpp" #include "graphics/renderer.hpp" #include "graphics/sprites.hpp" #include "gui/guiManager.hpp" #include "gui/window.hpp" #include "imgui/imguiWrapper.hpp" #include <GL/glew.h> #include <GLFW/glfw3.h> #include <cmath> #include <filesystem> #include <functional> #include <memory> #include <numbers> #include <sstream> #undef main struct Options { bool showImgui{true}; bool logTime{true}; bool logColors{false}; std::string logLevel{"DEBUG"}; }; Options Parse(int argc, char** argv) { Options values{}; struct option options[] = { {"help", no_argument, 0, 'h'}, {"log_colors", no_argument, 0, 'c'}, {"log_time", no_argument, 0, 't'}, {"log_level", required_argument, 0, 'l'}, {"imgui", no_argument, 0, 'i'}, }; int optionIndex = 0; int opt; while ((opt = getopt_long(argc, argv, "hctil:", options, &optionIndex)) != -1) { if (opt == 'h') { exit(0); } else if (opt == 'c') { values.logColors = true; } else if (opt == 't') { values.logTime = false; } else if (opt == 'i') { values.showImgui = false; } else if (opt == 'l') { values.logLevel = std::string{optarg}; } } return values; } int main(int argc, char** argv) { const auto options = Parse(argc, argv); const bool showImgui = options.showImgui; Logging::LogState::SetLogTime(options.logTime); Logging::LogState::SetLogColor(options.logColors); Logging::LogState::SetLevel(options.logLevel); auto log = std::ofstream{ std::filesystem::path{GetBakDirectory()} / "main3d.log" }; Logging::LogState::AddStream(&log); const auto& logger = Logging::LogState::GetLogger("main"); Logging::LogState::Disable("Compass"); Logging::LogState::Disable("DialogStore"); Logging::LogState::Disable("LoadEncounter"); Logging::LogState::Disable("LoadFixedObjects"); Logging::LogState::Disable("LoadSceneIndices"); Logging::LogState::Disable("LoadScenes"); Logging::LogState::Disable("MeshObjectStore"); Logging::LogState::Disable("GameData"); Logging::LogState::Disable("Gui::StaticTTM"); Logging::LogState::Disable("GuiRenderer"); //Logging::LogState::Disable("Gui::DialogRunner"); Logging::LogState::Disable("Gui::DialogDisplay"); Logging::LogState::Disable("Gui::AnimatorStore"); Logging::LogState::Disable("TeleportFactory"); Logging::LogState::Disable("FMAP_TWN"); Logging::LogState::Disable("FMAP"); Logging::LogState::Disable("CampData"); auto guiScalar = 4.0f; auto nativeWidth = 320.0f; auto nativeHeight = 200.0f; auto width = nativeWidth * guiScalar; auto height = nativeHeight * guiScalar; auto guiScaleInv = glm::vec2{1 / guiScalar, 1 / guiScalar}; /* OPEN GL / GLFW SETUP */ auto window = Graphics::MakeGlfwWindow( height, width, "BaK"); auto spriteManager = Graphics::SpriteManager{}; auto guiRenderer = Graphics::GuiRenderer{ width, height, guiScalar, spriteManager}; auto root = Gui::Window{ spriteManager, width / guiScalar, height / guiScalar}; auto gameState = BAK::GameState{nullptr}; auto guiManager = Gui::GuiManager{ root.GetCursor(), spriteManager, gameState }; root.AddChildFront(&guiManager); guiManager.EnterMainMenu(false); Camera lightCamera{ static_cast<unsigned>(width), static_cast<unsigned>(height), 400 * 30.0f, 2.0f}; lightCamera.UseOrthoMatrix(400, 400); Camera camera{ static_cast<unsigned>(width), static_cast<unsigned>(height), 400 * 30.0f, 2.0f}; Camera* cameraPtr = &camera; guiManager.mMainView.SetHeading(camera.GetHeading()); // OpenGL 3D Renderer constexpr auto sShadowDim = 4096; bool runningGame = false; auto renderer = Graphics::Renderer{ width, height, sShadowDim, sShadowDim}; Game::GameRunner gameRunner{ camera, gameState, guiManager, [&](auto& zoneData){ renderer.LoadData(zoneData.mObjects, zoneData.mZoneTextures); }}; // Wire up the zone loader to the GUI manager guiManager.SetZoneLoader(&gameRunner); auto currentTile = camera.GetGameTile(); logger.Info() << " Starting on tile: " << currentTile << "\n"; Graphics::Light light{ glm::vec3{.0, -.25, .00}, glm::vec3{.5, .5, .5}, glm::vec3{ 1, .85, .87}, glm::vec3{.2, .2, .2}, .0005f, glm::vec3{.15, .31, .36} }; const auto UpdateLightCamera = [&]{ const auto lightPos = camera.GetNormalisedPosition() - 100.0f * glm::normalize(light.mDirection); const auto diff = lightCamera.GetNormalisedPosition() - camera.GetNormalisedPosition(); const auto horizDistance = glm::sqrt((diff.x * diff.x) + (diff.z * diff.z)); const auto yAngle = -glm::atan(diff.y / horizDistance); const auto xAngle = glm::atan(diff.x, diff.z) - ((180.0f / 360.0f) * (2 * 3.141592)) ; lightCamera.SetAngle(glm::vec2{xAngle, yAngle}); lightCamera.SetPosition(lightPos * BAK::gWorldScale); }; auto UpdateGameTile = [&]() { if (camera.GetGameTile() != currentTile && gameRunner.mGameState.GetGameData()) { currentTile = camera.GetGameTile(); logger.Debug() << "New tile: " << currentTile << "\n"; gameRunner.mGameState.Apply(BAK::State::ClearTileRecentEncounters); } }; Graphics::InputHandler inputHandler{}; inputHandler.Bind(GLFW_KEY_G, [&]{ if (guiManager.InMainView()) cameraPtr = &camera; }); inputHandler.Bind(GLFW_KEY_H, [&]{ if (guiManager.InMainView()) cameraPtr = &lightCamera; }); inputHandler.Bind(GLFW_KEY_R, [&]{ if (guiManager.InMainView()) UpdateLightCamera(); }); inputHandler.Bind(GLFW_KEY_UP, [&]{ if (guiManager.InMainView()){cameraPtr->StrafeForward(); UpdateGameTile();}}); inputHandler.Bind(GLFW_KEY_DOWN, [&]{ if (guiManager.InMainView()){cameraPtr->StrafeBackward(); UpdateGameTile();}}); inputHandler.Bind(GLFW_KEY_LEFT, [&]{ if (guiManager.InMainView()){cameraPtr->StrafeLeft(); UpdateGameTile();}}); inputHandler.Bind(GLFW_KEY_RIGHT,[&]{ if (guiManager.InMainView()){cameraPtr->StrafeRight(); UpdateGameTile();}}); inputHandler.Bind(GLFW_KEY_W, [&]{ if (guiManager.InMainView()){cameraPtr->MoveForward(); UpdateGameTile();}}); inputHandler.Bind(GLFW_KEY_A, [&]{ if (guiManager.InMainView()){cameraPtr->StrafeLeft(); UpdateGameTile();}}); inputHandler.Bind(GLFW_KEY_D, [&]{ if (guiManager.InMainView()){cameraPtr->StrafeRight(); UpdateGameTile();}}); inputHandler.Bind(GLFW_KEY_S, [&]{ if (guiManager.InMainView()){cameraPtr->MoveBackward(); UpdateGameTile();}}); inputHandler.Bind(GLFW_KEY_Q, [&]{ if (guiManager.InMainView()) { cameraPtr->RotateLeft(); guiManager.mMainView.SetHeading(cameraPtr->GetHeading()); }}); inputHandler.Bind(GLFW_KEY_E, [&]{ if (guiManager.InMainView()) { cameraPtr->RotateRight(); guiManager.mMainView.SetHeading(cameraPtr->GetHeading()); }}); inputHandler.Bind(GLFW_KEY_X, [&]{ if (guiManager.InMainView()) cameraPtr->RotateVerticalUp(); }); inputHandler.Bind(GLFW_KEY_Y, [&]{ if (guiManager.InMainView()) cameraPtr->RotateVerticalDown(); }); inputHandler.Bind(GLFW_KEY_C, [&]{ if (guiManager.InMainView()) gameRunner.mGameState.Apply(BAK::State::ClearTileRecentEncounters); }); inputHandler.Bind(GLFW_KEY_BACKSPACE, [&]{ if (root.OnKeyEvent(Gui::KeyPress{GLFW_KEY_BACKSPACE})){ ;} }); inputHandler.BindCharacter([&](char character){ if(root.OnKeyEvent(Gui::Character{character})){ ;} }); Graphics::InputHandler::BindKeyboardToWindow(window.get(), inputHandler); Graphics::InputHandler::BindMouseToWindow(window.get(), inputHandler); inputHandler.BindMouse( GLFW_MOUSE_BUTTON_LEFT, [&](auto clickPos) { bool guiHandled = root.OnMouseEvent( Gui::LeftMousePress{guiScaleInv * clickPos}); if (!guiHandled && guiManager.InMainView()) { glDisable(GL_BLEND); glDisable(GL_MULTISAMPLE); renderer.DrawForPicking( gameRunner.mSystems->GetRenderables(), gameRunner.mSystems->GetSprites(), *cameraPtr); gameRunner.CheckClickable(renderer.GetClickedEntity(clickPos)); } }, [&](auto clickPos) { root.OnMouseEvent( Gui::LeftMouseRelease{guiScaleInv * clickPos}); } ); inputHandler.BindMouse( GLFW_MOUSE_BUTTON_RIGHT, [&](auto click) { root.OnMouseEvent( Gui::RightMousePress{guiScaleInv * click}); }, [&](auto click) { root.OnMouseEvent( Gui::RightMouseRelease{guiScaleInv * click}); } ); inputHandler.BindMouseMotion( [&](auto pos) { root.OnMouseEvent( Gui::MouseMove{guiScaleInv * pos}); } ); inputHandler.BindMouseScroll( [&](auto pos) { root.OnMouseEvent( Gui::MouseScroll{guiScaleInv * pos}); } ); double currentTime = 0; double lastTime = 0; float deltaTime = 0; glfwSetCursorPos(window.get(), width/2, height/2); //glfwSetInputMode(window.get(), GLFW_CURSOR, GLFW_CURSOR_HIDDEN); //glfwSetInputMode(window.get(), GLFW_CURSOR, GLFW_CURSOR_DISABLED); glEnable(GL_MULTISAMPLE); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LESS); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); double pointerPosX, pointerPosY; bool consoleOpen = true; auto console = Console{}; console.mCamera = &camera; console.mGameRunner = &gameRunner; console.mGuiManager = &guiManager; console.mGameState = &gameState; console.ToggleLog(); // Do this last so we don't blast Imgui's callback hooks if (showImgui) { ImguiWrapper::Initialise(window.get()); } do { currentTime = glfwGetTime(); deltaTime = float(currentTime - lastTime); guiManager.OnTimeDelta(currentTime - lastTime); lastTime = currentTime; cameraPtr->SetDeltaTime(deltaTime); if (gameRunner.mGameState.GetGameData()) { if (guiManager.InMainView()) { gameState.SetLocation(cameraPtr->GetGameLocation()); } } glfwPollEvents(); glfwGetCursorPos(window.get(), &pointerPosX, &pointerPosY); inputHandler.HandleInput(window.get()); // { *** Draw 3D World *** UpdateLightCamera(); glEnable(GL_BLEND); glEnable(GL_MULTISAMPLE); if (gameRunner.mGameState.GetGameData() != nullptr) { double bakTimeOfDay = (gameState.GetWorldTime().GetTime().mTime % 43200); auto twoPi = std::numbers::pi_v<double> * 2.0; // light starts at 6 after midnight auto sixHours = 7200.0; auto beginDay = bakTimeOfDay - sixHours; bool isNight = bakTimeOfDay < 7200|| bakTimeOfDay > 36000; light.mDirection = glm::vec3{ std::cos(beginDay * (twoPi / (28800 * 2))), isNight ? .1 : -.25, 0}; float ambient = isNight ? .05 : std::sin(beginDay * (twoPi / 57600)); light.mAmbientColor = glm::vec3{ambient}; light.mDiffuseColor = ambient * glm::vec3{ 1., std::sin(beginDay * (twoPi / (57600 * 2))), std::sin(beginDay * (twoPi / (57600 * 2))) }; light.mSpecularColor = isNight ? glm::vec3{0} : ambient * glm::vec3{ 1., std::sin(beginDay * (twoPi / (57600 * 2))), std::sin(beginDay * (twoPi / (57600 * 2))) }; light.mFogColor = ambient * glm::vec3{.15, .31, .36}; renderer.BeginDepthMapDraw(); renderer.DrawDepthMap( gameRunner.mSystems->GetRenderables(), lightCamera); renderer.DrawDepthMap( gameRunner.mSystems->GetSprites(), lightCamera); renderer.EndDepthMapDraw(); glViewport(0, 0, static_cast<GLsizei>(width), static_cast<GLsizei>(height)); // Dark blue background glClearColor(ambient * 0.15f, ambient * 0.31f, ambient * 0.36f, 0.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); renderer.DrawWithShadow( gameRunner.mSystems->GetRenderables(), light, lightCamera, *cameraPtr); renderer.DrawWithShadow( gameRunner.mSystems->GetSprites(), light, lightCamera, *cameraPtr); } //// { *** Draw 2D GUI *** guiRenderer.RenderGui(&root); // { *** IMGUI START *** if (showImgui) { ImGui_ImplOpenGL3_NewFrame(); ImGui_ImplGlfw_NewFrame(); ImGui::NewFrame(); ShowLightGui(light); ShowCameraGui(camera); console.Draw("Console", &consoleOpen); } if (gameRunner.mGameState.GetGameData() && guiManager.InMainView()) { gameRunner.RunGameUpdate(); //BAK::PlayBackgroundSounds(gameRunner.mGameState); } if (showImgui && gameRunner.mActiveEncounter) { ImGui::Begin("Encounter"); std::stringstream ss{}; ss << "Encounter: " << *gameRunner.mActiveEncounter << std::endl; ImGui::TextWrapped(ss.str().c_str()); ImGui::End(); const auto& encounter = gameRunner.mActiveEncounter->GetEncounter(); std::visit( overloaded{ [&](const BAK::Encounter::GDSEntry& gds){ ShowDialogGui( gds.mEntryDialog, BAK::DialogStore::Get(), gameRunner.mGameState.GetGameData()); }, [&](const BAK::Encounter::Block& e){ ShowDialogGui( e.mDialog, BAK::DialogStore::Get(), gameRunner.mGameState.GetGameData()); }, [&](const BAK::Encounter::Combat& e){ ShowDialogGui( e.mEntryDialog, BAK::DialogStore::Get(), gameRunner.mGameState.GetGameData()); }, [&](const BAK::Encounter::Dialog& e){ ShowDialogGui( e.mDialog, BAK::DialogStore::Get(), gameRunner.mGameState.GetGameData()); }, [](const BAK::Encounter::EventFlag&){ }, [&](const BAK::Encounter::Zone& e){ ShowDialogGui( e.mDialog, BAK::DialogStore::Get(), gameRunner.mGameState.GetGameData()); }, }, encounter); } if (showImgui) { ImguiWrapper::Draw(window.get()); } if (showImgui) { auto& io = ImGui::GetIO(); if (io.WantCaptureKeyboard || io.WantCaptureMouse) { inputHandler.SetHandleInput(false); } else { inputHandler.SetHandleInput(true); } } else { inputHandler.SetHandleInput(true); } // *** IMGUI END *** } glfwSwapBuffers(window.get()); } while (glfwGetKey(window.get(), GLFW_KEY_ESCAPE) != GLFW_PRESS && glfwWindowShouldClose(window.get()) == 0); if (showImgui) { ImguiWrapper::Shutdown(); } return 0; }
17,420
C++
.cpp
465
27.619355
139
0.572531
xavieran/BaKGL
39
2
32
GPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,416
play_cutscene.cpp
xavieran_BaKGL/app/play_cutscene.cpp
#include "com/algorithm.hpp" #include "com/logger.hpp" #include "com/visit.hpp" #include "bak/cutscenes.hpp" #include "graphics/glfw.hpp" #include "graphics/guiRenderer.hpp" #include "graphics/inputHandler.hpp" #include "graphics/texture.hpp" #include "gui/actors.hpp" #include "gui/animatorStore.hpp" #include "gui/backgrounds.hpp" #include "gui/cutscenePlayer.hpp" #include "gui/core/mouseEvent.hpp" #include "gui/guiManager.hpp" #include "gui/window.hpp" #include "imgui/imguiWrapper.hpp" #include <GL/glew.h> #include <GLFW/glfw3.h> #include <functional> #include <memory> #include <sstream> // SDL... #undef main int main(int argc, char** argv) { const auto& logger = Logging::LogState::GetLogger("main"); Logging::LogState::SetLevel(Logging::LogLevel::Debug); Logging::LogState::Disable("LoadScenes"); Logging::LogState::Disable("LoadSceneIndices"); Logging::LogState::Disable("DialogStore"); Logging::LogState::Disable("Gui::Actors"); Logging::LogState::Disable("CreateFileBuffer"); auto guiScalar = 3.5f; auto nativeWidth = 320.0f; auto nativeHeight = 240.0f; auto width = nativeWidth * guiScalar; auto height = nativeHeight * guiScalar * 0.83f; auto window = Graphics::MakeGlfwWindow( height, width, "Show GUI"); //auto guiScale = glm::vec3{guiScalar, guiScalar, 0}; auto guiScaleInv = glm::vec2{1 / guiScalar, 1 / guiScalar}; glViewport(0, 0, width, height); ImguiWrapper::Initialise(window.get()); // Dark blue background glClearColor(0.0f, 0.0f, 0.0, 0.0f); auto spriteManager = Graphics::SpriteManager{}; auto guiRenderer = Graphics::GuiRenderer{ width, height, guiScalar, spriteManager}; if (argc < 2) { std::cerr << "Usage: " << argv[0] << " CHAPTER\n"; return -1; } std::string basename{argv[1]}; const auto font = Gui::Font{"GAME.FNT", spriteManager}; const auto bookFont = Gui::Font{"BOOK.FNT", spriteManager}; const auto actors = Gui::Actors{spriteManager}; const auto backgrounds = Gui::Backgrounds{spriteManager}; Gui::Window rootWidget{ spriteManager, width / guiScalar, height / guiScalar}; auto gameState = BAK::GameState{nullptr}; auto guiManager = Gui::GuiManager{ rootWidget.GetCursor(), spriteManager, gameState }; auto chapter = BAK::Chapter{static_cast<unsigned>(std::atoi(argv[1]))}; auto startActions = BAK::CutsceneList::GetStartScene(chapter); auto finishActions = BAK::CutsceneList::GetFinishScene(chapter); std::vector<BAK::CutsceneAction> actions{}; for (const auto& action : startActions) { actions.emplace_back(action); } for (const auto& action : finishActions) { actions.emplace_back(action); } rootWidget.AddChildFront(&guiManager); bool playing = false; // Set up input callbacks Graphics::InputHandler inputHandler{}; Graphics::InputHandler::BindMouseToWindow(window.get(), inputHandler); Graphics::InputHandler::BindKeyboardToWindow(window.get(), inputHandler); inputHandler.BindMouse( GLFW_MOUSE_BUTTON_LEFT, [&](const auto click) { rootWidget.OnMouseEvent( Gui::LeftMousePress{guiScaleInv * click}); }, [&](const auto click) { rootWidget.OnMouseEvent( Gui::LeftMouseRelease{guiScaleInv * click}); } ); inputHandler.BindMouse( GLFW_MOUSE_BUTTON_RIGHT, [&](auto click) { rootWidget.OnMouseEvent( Gui::RightMousePress{guiScaleInv * click}); }, [&](auto click) { rootWidget.OnMouseEvent( Gui::RightMouseRelease{guiScaleInv * click}); } ); inputHandler.BindMouseMotion( [&](auto pos) { rootWidget.OnMouseEvent( Gui::MouseMove{guiScaleInv * pos}); } ); // Graphics stuff glfwSetInputMode(window.get(), GLFW_CURSOR, GLFW_CURSOR_HIDDEN); glEnable(GL_MULTISAMPLE); glDisable(GL_DEPTH_TEST); glDepthFunc(GL_LESS); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); double currentTime = 0; double lastTime = 0; guiManager.PlayCutscene(actions, []{}); do { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); currentTime = glfwGetTime(); guiManager.OnTimeDelta(currentTime - lastTime); lastTime = currentTime; guiRenderer.RenderGui(&rootWidget); glfwSwapBuffers(window.get()); glfwPollEvents(); } while (glfwGetKey(window.get(), GLFW_KEY_ESCAPE) != GLFW_PRESS && glfwWindowShouldClose(window.get()) == 0); ImguiWrapper::Shutdown(); return 0; }
4,954
C++
.cpp
150
26.326667
77
0.647679
xavieran/BaKGL
39
2
32
GPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,417
guiMultiple.cpp
xavieran_BaKGL/app/guiMultiple.cpp
#include "com/logger.hpp" #include "com/ostream.hpp" #include "graphics/inputHandler.hpp" #include "graphics/glm.hpp" #include "graphics/glfw.hpp" #include "graphics/guiRenderer.hpp" #include "gui/window.hpp" #include "gui/icons.hpp" #include "imgui/imguiWrapper.hpp" #include <GLFW/glfw3.h> #include <glm/glm.hpp> #include <memory> #include <sstream> int main(int argc, char** argv) { const auto& logger = Logging::LogState::GetLogger("main"); Logging::LogState::SetLevel(Logging::LogLevel::Debug); auto guiScalar = 4.0f; auto width = 1600.0f; auto height = 1000.0f; auto window = Graphics::MakeGlfwWindow( height, width, "BMX Explorer"); glViewport(0, 0, width, height); ImguiWrapper::Initialise(window.get()); // Dark blue background glClearColor(0.15f, 0.31f, 0.36f, 0.0f); auto spriteManager = Graphics::SpriteManager{}; auto guiRenderer = Graphics::GuiRenderer{ width, height, guiScalar, spriteManager}; auto root = Gui::Window{ spriteManager, width / guiScalar, height / guiScalar}; auto icons = Gui::Icons{spriteManager}; unsigned iconI = 0; auto picture = Gui::Widget{ Gui::ImageTag{}, Graphics::SpriteSheetIndex{1}, Graphics::TextureIndex{0}, glm::vec2{0,0}, glm::vec2{100,100}, true}; root.AddChildBack(&picture); root.HideCursor(); auto vao = Graphics::VertexArrayObject{}; vao.BindGL(); const auto& ss = spriteManager.GetSpriteSheet(Graphics::SpriteSheetIndex{1}); auto buffers = Graphics::GLBuffers{}; logger.Debug() << "Made buffers\n"; // vertices std::vector<glm::vec3> vertices{}; std::vector<unsigned> indices{}; auto transform = std::vector<glm::vec4>{}; auto texCoords = std::vector<glm::vec4>{}; auto colorModes = std::vector<unsigned>{}; auto colors = std::vector<glm::vec4>{}; auto params = std::vector<glm::ivec4>{}; unsigned objs = 20; unsigned index = 0; auto pos = glm::vec2{0, 60}; for (unsigned objectIndex = 1; objectIndex < (ss.mObjects.mTextureCoords.size() / 6 - 1); objectIndex++) { const auto dim1 = ss.GetDimensions(objectIndex % objs); pos += glm::vec2{dim1.x / 2, 0}; const auto [o, l] = ss.mObjects.GetObject(0); for (unsigned i = 0; i < l; i++) { transform.emplace_back(guiScalar * glm::vec4{pos.x, pos.y, dim1.x, dim1.y}); colorModes.emplace_back(0); colors.emplace_back(glm::vec4{1}); params.emplace_back(glm::ivec4{0, objectIndex % objs, objectIndex, 0}); vertices.emplace_back(ss.mObjects.mVertices[i]); indices.emplace_back(index++); const auto& tex = ss.mObjects.mTextureCoords[objectIndex * 6 + i]; logger.Debug() << "ob: " << objectIndex << " i: " << i << " " << ss.mObjects.mTextureCoords.size() << std::endl; texCoords.emplace_back(glm::vec4{tex.x, tex.y, tex.z, 0}); } } logger.Debug() << "Vertices: " << vertices << "\n"; logger.Debug() << "Indices: " << indices << "\n"; // view matrix const auto viewMatrix = guiRenderer.mCamera.mViewMatrix; logger.Debug() << " " << vertices.size() << " " << texCoords.size() << " " << " " << colorModes.size() << " "<< colors.size() << " " << transform.size() << " " << ss.mSpriteDimensions.size() << "\n"; using namespace Graphics; buffers.AddStaticArrayBuffer<glm::vec3>("vertex", GLLocation{0}); buffers.AddStaticArrayBuffer<glm::vec4>("color", GLLocation{1}); buffers.AddStaticArrayBuffer<glm::vec4>("transform", GLLocation{2}); buffers.AddStaticArrayBuffer<glm::vec4>("params", GLLocation{3}); buffers.AddStaticArrayBuffer<glm::vec4>("texCoords", GLLocation{4}); buffers.AddElementBuffer("elements"); buffers.LoadBufferDataGL("vertex", vertices); buffers.LoadBufferDataGL("color", colors); buffers.LoadBufferDataGL("transform", transform); buffers.LoadBufferDataGL("params", params); buffers.LoadBufferDataGL("texCoords", texCoords); buffers.LoadBufferDataGL("elements", indices); buffers.SetAttribDivisor("vertex", 0); buffers.SetAttribDivisor("texCoords", 0); buffers.SetAttribDivisor("color", 0); buffers.SetAttribDivisor("transform", 0); buffers.SetAttribDivisor("params", 0); buffers.BindArraysGL(); auto shaderProgram = ShaderProgram{ "guiMultiple.vert.glsl", //"geometry.glsl", "guiMultiple.frag.glsl"}.Compile(); Graphics::InputHandler inputHandler{}; Graphics::InputHandler::BindMouseToWindow(window.get(), inputHandler); Graphics::InputHandler::BindKeyboardToWindow(window.get(), inputHandler); bool useOriginal = true; inputHandler.Bind(GLFW_KEY_K, [&]{ useOriginal = !useOriginal; }); unsigned k = 0; inputHandler.Bind(GLFW_KEY_R, [&]{ auto params = std::vector<glm::ivec4>{}; for (unsigned i = k++; i < ss.mSpriteDimensions.size(); i++) params.emplace_back(glm::ivec4{0, i % objs, i, 0}); buffers.LoadBufferDataGL("params", params); }); inputHandler.Bind(GLFW_KEY_RIGHT, [&]{ iconI++; picture.SetTexture(Graphics::TextureIndex{iconI}); logger.Debug() << "Pic: " << picture << "\n"; }); inputHandler.Bind(GLFW_KEY_LEFT, [&]{ iconI--; const auto& [ss, ti, dims] = icons.GetInventoryLockIcon(iconI); picture.SetSpriteSheet(ss); picture.SetTexture(ti); picture.SetDimensions(dims); logger.Debug() << "Pic: " << picture << "\n"; }); double currentTime = 0; double lastTime = 0; float deltaTime = 0; glfwSetCursorPos(window.get(), width / 2, height / 2); glEnable(GL_MULTISAMPLE); //glEnable(GL_DEPTH_TEST); glDisable(GL_DEPTH_TEST); glDepthFunc(GL_LESS); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); double pointerPosX, pointerPosY; double acc = 0; unsigned i = 0; do { currentTime = glfwGetTime(); deltaTime = float(currentTime - lastTime); acc += deltaTime; if (acc > .2) { i = (i + 1) % 20; acc = 0; } lastTime = currentTime; glfwPollEvents(); glfwGetCursorPos(window.get(), &pointerPosX, &pointerPosY); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // { *** Draw 2D GUI *** if (useOriginal) { guiRenderer.RenderGui(&root); } else { vao.BindGL(); shaderProgram.UseProgramGL(); glActiveTexture(GL_TEXTURE0); ss.mTextureBuffer.BindGL(); // bind tex... shaderProgram.SetUniform( shaderProgram.GetUniformLocation("V"), viewMatrix); shaderProgram.SetUniform( shaderProgram.GetUniformLocation("texture0"), 0); glDrawElements( GL_TRIANGLES, 6 * objs, GL_UNSIGNED_INT, (void*) 0); } glfwSwapBuffers(window.get()); } while (glfwGetKey(window.get(), GLFW_KEY_ESCAPE) != GLFW_PRESS && glfwWindowShouldClose(window.get()) == 0); ImguiWrapper::Shutdown(); glfwTerminate(); return 0; }
7,491
C++
.cpp
195
30.851282
133
0.615023
xavieran/BaKGL
39
2
32
GPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,418
display_encounters.cpp
xavieran_BaKGL/app/display_encounters.cpp
#include "com/logger.hpp" #include "bak/encounter/encounter.hpp" #include "bak/encounter/combat.ipp" #include "bak/zoneReference.hpp" #include "bak/monster.hpp" #include "bak/file/fileBuffer.hpp" int main(int argc, char** argv) { const auto& logger = Logging::LogState::GetLogger("main"); Logging::LogState::SetLevel(Logging::LogLevel::Spam); //BAK::Encounter::GenericCombatFactory<false>(); //BAK::Encounter::DialogFactory(); //BAK::Encounter::BlockFactory(); //BAK::Encounter::ZoneFactory(); //BAK::Encounter::EnableFactory(); //const auto ef = BAK::Encounter::EncounterFactory{}; //for (unsigned zone = 1; zone < 12; zone++) //{ // auto zoneLabel = BAK::ZoneLabel{zone}; // const auto tiles = BAK::LoadZoneRef(zoneLabel.GetZoneReference()); // for (unsigned tileIndex = 0; tileIndex < tiles.size(); tileIndex++) // { // const auto& tile = tiles[tileIndex]; // const auto x = tile.x; // const auto y = tile.y; // const auto tileData = zoneLabel.GetTileData(x ,y); // if (BAK::FileBufferFactory::Get().DataBufferExists(tileData)) // { // auto fb = BAK::FileBufferFactory::Get().CreateDataBuffer(tileData); // for (unsigned c = 1; c < 11; c++) // { // logger.Info() << "Loading world tile:" << zone << " " << x // << "," << y << " c: " << c << "\n"; // const auto encounters = BAK::Encounter::LoadEncounters( // ef, fb, BAK::Chapter{c}, glm::vec<2, unsigned>(x, y), tileIndex); // for (const auto& encounter : encounters) // logger.Info() << "Encounter: " << encounter << "\n"; // } // } // } //} return 0; }
1,888
C++
.cpp
43
39.44186
99
0.540098
xavieran/BaKGL
39
2
32
GPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,419
dialog_explorer.cpp
xavieran_BaKGL/app/dialog_explorer.cpp
#include "bak/dialog.hpp" #include "bak/dialogTarget.hpp" #include "bak/gameData.hpp" #include "com/logger.hpp" #include "imgui/imguiWrapper.hpp" #include "imgui/imgui.h" #include "imgui/imgui_impl_glfw.h" #include "imgui/imgui_impl_opengl3.h" #include <GL/glew.h> #include <GLFW/glfw3.h> #include <stack> int main(int argc, char** argv) { const auto& logger = Logging::LogState::GetLogger("main"); Logging::LogState::SetLevel(Logging::LogLevel::Debug); BAK::ZoneLabel zoneLabel{"Z01"}; std::unique_ptr<BAK::GameData> gameData{nullptr}; if (argc == 2) gameData = std::make_unique<BAK::GameData>(argv[1]); const auto& dialogStore = BAK::DialogStore::Get(); if( !glfwInit() ) { logger.Error() << "Failed to initialize GLFW" << std::endl; std::exit(1); } GLFWwindow* window; const unsigned antiAliasingSamples = 4; glfwWindowHint(GLFW_SAMPLES, antiAliasingSamples); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); unsigned height = 800; unsigned width = 600; /*unsigned height = 1600; unsigned width = 2400;*/ window = glfwCreateWindow(width, height, argc == 2 ? argv[1] : "Dialog Explorer", NULL, NULL); if( window == NULL ) { logger.Log(Logging::LogLevel::Error) << "Failed to open GLFW window" << std::endl; glfwTerminate(); std::exit(1); } glfwMakeContextCurrent(window); // Initialize GLEW glewExperimental = true; // Needed for core profile if (glewInit() != GLEW_OK) { logger.Log(Logging::LogLevel::Error) << "Failed to initialize GLEW" << std::endl; glfwTerminate(); return -1; } // Ensure we can capture the escape key being pressed below glfwSetInputMode(window, GLFW_STICKY_KEYS, GL_TRUE); ImguiWrapper::Initialise(window); // Dark blue background glClearColor(0.15f, 0.31f, 0.36f, 0.0f); auto history = std::stack<BAK::Target>{}; //auto current = dialogIndex.GetKeys().front(); auto current = BAK::Target{BAK::KeyTarget{0x72}}; do { glfwPollEvents(); // Start the Dear ImGui frame ImGui_ImplOpenGL3_NewFrame(); ImGui_ImplGlfw_NewFrame(); ImGui::NewFrame(); { if (!dialogStore.HasSnippet(current)) current = BAK::KeyTarget{0x72}; const auto& snippet = dialogStore.GetSnippet(current); const ImGuiViewport* viewport = ImGui::GetMainViewport(); bool use_work_area = true; ImGui::SetNextWindowPos(use_work_area ? viewport->WorkPos : viewport->Pos); ImGui::SetNextWindowSize(use_work_area ? viewport->WorkSize : viewport->Size); ImGui::Begin("Dialog"); //ImGui::Text("Dialog indices: %zu", dialogIndex.GetKeys().size()); static char curIndex[64] = "0"; ImGui::InputText("Index ", curIndex, 10); //, ImGuiInputTextFlags_CharsHex); ImGui::SameLine(); if (ImGui::Button("Change")) { while (!history.empty()) history.pop(); //current = dialogIndex.GetKeys()[atoi(curIndex)];Q std::stringstream ss{}; ss << std::hex << curIndex; std::uint32_t key; ss >> key; current = BAK::KeyTarget{key}; logger.Info() << "Change Key to: " << current << std::endl; } { std::stringstream ss{}; ss << "Previous: "; if (ImGui::Button("Back") && (!history.empty())) { current = history.top(); history.pop(); } if (!history.empty()) ss << history.top(); else ss << "[None]"; ss << " Current: " << current; ImGui::Text(ss.str().c_str()); } { std::stringstream ss{}; ss << "[ ds: " << std::hex << +snippet.mDisplayStyle << " act: " << +snippet.mActor << " ds2: " << +snippet.mDisplayStyle2 << " ds3: " << +snippet.mDisplayStyle3 << " ]" << std::endl; for (const auto& action : snippet.mActions) ss << "Action :: " << action << std::endl; ImGui::TextWrapped(ss.str().c_str()); } ImGui::TextWrapped("Text:\n %s", snippet.GetText().data()); for (const auto& choice : snippet.GetChoices()) { std::stringstream ss{}; ss << choice; if (ImGui::Button(ss.str().c_str())) { history.push(current); current = choice.mTarget; } //if (gameData != nullptr) //{ // ss.str(""); ss << "Val: " << gameData->ReadEvent(choice.mState) << " Word: " << std::hex << gameData->ReadEventWord(choice.mState) // << " @state: " << choice.mState; // ImGui::SameLine(); ImGui::Text(ss.str().c_str()); //} if (choice.mTarget != BAK::Target{BAK::KeyTarget{0}}) { ImGui::TextWrapped(dialogStore.GetFirstText( dialogStore.GetSnippet(choice.mTarget)).substr(0, 40).data()); } } ImGui::End(); } glClear(GL_COLOR_BUFFER_BIT); ImguiWrapper::Draw(window); // Swap buffers glfwSwapBuffers(window); } // Check if the ESC key was pressed or the window was closed while (glfwGetKey(window, GLFW_KEY_ESCAPE) != GLFW_PRESS && glfwWindowShouldClose(window) == 0); ImguiWrapper::Shutdown(); glfwDestroyWindow(window); glfwTerminate(); return 0; }
5,996
C++
.cpp
144
30.944444
152
0.550597
xavieran/BaKGL
39
2
32
GPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,420
display_object.cpp
xavieran_BaKGL/app/display_object.cpp
#include "com/logger.hpp" #include "bak/palette.hpp" #include "bak/camera.hpp" #include "bak/worldFactory.hpp" #include "bak/zone.hpp" #include "game/systems.hpp" #include "graphics/glfw.hpp" #include "graphics/inputHandler.hpp" #include "graphics/renderer.hpp" #include "graphics/meshObject.hpp" #include "graphics/opengl.hpp" #include "graphics/shaderProgram.hpp" #include <GL/glew.h> #include <GLFW/glfw3.h> #include <glm/gtc/type_ptr.hpp> int main(int argc, char** argv) { const auto& logger = Logging::LogState::GetLogger("display_object"); Logging::LogState::SetLevel(Logging::LogLevel::Debug); Logging::LogState::SetLogTime(false); Logging::LogState::Disable("Combat"); Logging::LogState::Disable("CreateFileBuffer"); Logging::LogState::Disable("LoadFixedObjects"); Logging::LogState::Disable("MeshObjectStore"); //Logging::LogState::Disable("ZoneItemToMeshObject"); Logging::LogState::Disable("World"); Logging::LogState::Disable("LoadEncounter"); Logging::LogState::Disable("ZoneFactory"); Logging::LogState::Disable("ShaderProgram"); Logging::LogState::Disable("GLBuffers"); if (argc != 3) { logger.Error() << "Call with <ZONE> <OBJECT>" << std::endl; std::exit(1); } auto objectToDisplay = argv[2]; auto zoneData = std::make_unique<BAK::Zone>(std::atoi(argv[1])); auto guiScalar = 6.0f; auto nativeWidth = 320.0f; auto nativeHeight = 200.0f; auto width = nativeWidth * guiScalar; auto height = nativeHeight * guiScalar; auto window = Graphics::MakeGlfwWindow( height, width, "BaK"); auto renderer = Graphics::Renderer{ width, height, 1024, 1024}; renderer.LoadData(zoneData->mObjects, zoneData->mZoneTextures); Camera lightCamera{ static_cast<unsigned>(width), static_cast<unsigned>(height), 400 * 30.0f, 2.0f}; lightCamera.UseOrthoMatrix(400, 400); Camera camera{ static_cast<unsigned>(width), static_cast<unsigned>(height), 50*30.0f, 2.0f}; Camera* cameraPtr = &camera; camera.SetPosition({-10, 0, -10}); Graphics::Light light{ glm::vec3{.2, -.1, .05}, glm::vec3{.5, .5, .5}, glm::vec3{1,.85,.87}, glm::vec3{.2,.2,.2}, .0005f, glm::vec3{.15, .31, .36} }; auto systems = Systems{}; auto renderable = Renderable{ systems.GetNextItemId(), zoneData->mObjects.GetObject(objectToDisplay), {0,0,0}, {0,0,0}, glm::vec3{1.0f}}; systems.AddRenderable(renderable); glfwSetCursorPos(window.get(), width/2, height/2); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_MULTISAMPLE); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LESS); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // Dark blue background glClearColor(0.0f, 0.0f, 0.4f, 0.0f); Graphics::InputHandler inputHandler{}; inputHandler.Bind(GLFW_KEY_W, [&]{ cameraPtr->MoveForward(); }); inputHandler.Bind(GLFW_KEY_S, [&]{ cameraPtr->MoveBackward(); }); inputHandler.Bind(GLFW_KEY_A, [&]{ cameraPtr->StrafeLeft(); }); inputHandler.Bind(GLFW_KEY_D, [&]{ cameraPtr->StrafeRight(); }); inputHandler.Bind(GLFW_KEY_X, [&]{ cameraPtr->RotateVerticalUp(); }); inputHandler.Bind(GLFW_KEY_Y, [&]{ cameraPtr->RotateVerticalDown(); }); inputHandler.Bind(GLFW_KEY_Q, [&]{ cameraPtr->RotateLeft(); }); inputHandler.Bind(GLFW_KEY_E, [&]{ cameraPtr->RotateRight(); }); Graphics::InputHandler::BindKeyboardToWindow(window.get(), inputHandler); Graphics::InputHandler::BindMouseToWindow(window.get(), inputHandler); double currentTime; double lastTime = 0; float deltaTime; do { currentTime = glfwGetTime(); deltaTime = float(currentTime - lastTime); lastTime = currentTime; cameraPtr->SetDeltaTime(deltaTime); inputHandler.HandleInput(window.get()); glViewport(0, 0, static_cast<GLsizei>(width), static_cast<GLsizei>(height)); // Dark blue background glClearColor(0.15f, 0.31f, 0.36f, 0.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); renderer.DrawWithShadow( systems.GetRenderables(), light, lightCamera, *cameraPtr); // Swap buffers glfwSwapBuffers(window.get()); glfwPollEvents(); } // Check if the ESC key was pressed or the window was closed while (glfwGetKey(window.get(), GLFW_KEY_ESCAPE ) != GLFW_PRESS && glfwWindowShouldClose(window.get()) == 0 ); return 0; }
4,741
C++
.cpp
128
30.671875
84
0.649595
xavieran/BaKGL
39
2
32
GPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,421
display_tbl.cpp
xavieran_BaKGL/app/display_tbl.cpp
#include "bak/model.hpp" #include "bak/dataTags.hpp" #include "com/ostream.hpp" #include <set> #include <unordered_map> #include "com/logger.hpp" int main(int argc, char** argv) { const auto& logger = Logging::LogState::GetLogger("main"); Logging::LogState::SetLevel(Logging::LogLevel::Spam); std::string tbl{argv[1]}; auto tblBuf = BAK::FileBufferFactory::Get().CreateDataBuffer(tbl); logger.Info() << "Loading TBL:" << tbl << std::endl; auto models = BAK::LoadTBL(tblBuf); for (unsigned i = 0; i < models.size(); i++) { logger.Info() << "Model #" << i << " " << models[i].mName << "\n"; } return 0; }
660
C++
.cpp
20
29.15
74
0.633914
xavieran/BaKGL
39
2
32
GPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,422
display_spells.cpp
xavieran_BaKGL/app/display_spells.cpp
#include "bak/spells.hpp" #include "bak/camp.hpp" #include "bak/fileBufferFactory.hpp" #include "com/logger.hpp" int main(int argc, char** argv) { const auto& logger = Logging::LogState::GetLogger("main"); Logging::LogState::SetLevel(Logging::LogLevel::Debug); Logging::LogState::Disable("DialogStore"); BAK::SpellDatabase::Get(); BAK::PowerRing::Get(); //for (unsigned i = 0; i < 6; i++) //{ // BAK::SymbolLines::GetPoints(i); //} return 0; }
495
C++
.cpp
17
25.294118
62
0.653191
xavieran/BaKGL
39
2
32
GPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,423
display_book.cpp
xavieran_BaKGL/app/display_book.cpp
#include "bak/book.hpp" #include "com/logger.hpp" #include "bak/fileBufferFactory.hpp" int main(int argc, char** argv) { const auto& logger = Logging::LogState::GetLogger("main"); Logging::LogState::SetLevel(Logging::LogLevel::Debug); if (argc < 2) { std::cerr << "No arguments provided!\nUsage: " << argv[0] << " BOK\n"; return -1; } std::string bokFile{argv[1]}; auto fb = BAK::FileBufferFactory::Get().CreateDataBuffer(bokFile); auto book = BAK::LoadBook(fb); logger.Info() << book << "\n"; return 0; }
586
C++
.cpp
19
25.631579
70
0.621622
xavieran/BaKGL
39
2
32
GPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,424
display_sound.cpp
xavieran_BaKGL/app/display_sound.cpp
#include "audio/audio.hpp" #include "com/logger.hpp" #undef main int main(int argc, char** argv) { const auto& logger = Logging::LogState::GetLogger("main"); Logging::LogState::SetLevel(Logging::LogLevel::Spam); std::string soundOrMusic{argv[1]}; std::string soundIndexStr{argv[2]}; logger.Info() << "Sound index:" << soundIndexStr << std::endl; std::stringstream ss{}; ss << soundIndexStr; unsigned index; ss >> index; if (soundOrMusic == "m") { AudioA::AudioManager::Get().ChangeMusicTrack(AudioA::MusicIndex{index}); } if (soundOrMusic == "s") { AudioA::AudioManager::Get().PlaySound(AudioA::SoundIndex{index}); } std::this_thread::sleep_for(std::chrono::milliseconds{5000}); return 0; }
788
C++
.cpp
25
26.64
80
0.656
xavieran/BaKGL
39
2
32
GPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,425
play_ttm.cpp
xavieran_BaKGL/app/play_ttm.cpp
#include "com/algorithm.hpp" #include "com/logger.hpp" #include "com/visit.hpp" #include "graphics/glfw.hpp" #include "graphics/guiRenderer.hpp" #include "graphics/inputHandler.hpp" #include "graphics/texture.hpp" #include "gui/actors.hpp" #include "gui/animatorStore.hpp" #include "gui/backgrounds.hpp" #include "gui/cutscenePlayer.hpp" #include "gui/core/mouseEvent.hpp" #include "gui/window.hpp" #include "imgui/imguiWrapper.hpp" #include <GL/glew.h> #include <GLFW/glfw3.h> #include <functional> #include <memory> #include <sstream> // SDL... #undef main int main(int argc, char** argv) { const auto& logger = Logging::LogState::GetLogger("main"); Logging::LogState::SetLevel(Logging::LogLevel::Debug); Logging::LogState::Disable("LoadScenes"); Logging::LogState::Disable("LoadSceneIndices"); Logging::LogState::Disable("DialogStore"); Logging::LogState::Disable("Gui::Actors"); Logging::LogState::Disable("CreateFileBuffer"); auto guiScalar = 3.5f; auto nativeWidth = 320.0f; auto nativeHeight = 240.0f; auto width = nativeWidth * guiScalar; auto height = nativeHeight * guiScalar * 0.83f; auto window = Graphics::MakeGlfwWindow( height, width, "Show GUI"); //auto guiScale = glm::vec3{guiScalar, guiScalar, 0}; auto guiScaleInv = glm::vec2{1 / guiScalar, 1 / guiScalar}; glViewport(0, 0, width, height); ImguiWrapper::Initialise(window.get()); // Dark blue background glClearColor(0.0f, 0.0f, 0.0, 0.0f); auto spriteManager = Graphics::SpriteManager{}; auto guiRenderer = Graphics::GuiRenderer{ width, height, guiScalar, spriteManager}; if (argc < 2) { std::cerr << "Usage: " << argv[0] << " BASENAME\n"; return -1; } std::string basename{argv[1]}; const auto font = Gui::Font{"GAME.FNT", spriteManager}; const auto bookFont = Gui::Font{"BOOK.FNT", spriteManager}; const auto actors = Gui::Actors{spriteManager}; const auto backgrounds = Gui::Backgrounds{spriteManager}; Gui::Window rootWidget{ spriteManager, width / guiScalar, height / guiScalar}; Gui::AnimatorStore animatorStore{}; auto dynamicTTM = Gui::DynamicTTM( spriteManager, animatorStore, font, backgrounds, [&](){ }, [&](auto book){ }); rootWidget.AddChildBack(dynamicTTM.GetScene()); dynamicTTM.BeginScene(basename + ".ADS", basename + ".TTM"); bool playing = false; // Set up input callbacks Graphics::InputHandler inputHandler{}; Graphics::InputHandler::BindMouseToWindow(window.get(), inputHandler); Graphics::InputHandler::BindKeyboardToWindow(window.get(), inputHandler); inputHandler.BindMouse( GLFW_MOUSE_BUTTON_LEFT, [&](const auto click) { rootWidget.OnMouseEvent( Gui::LeftMousePress{guiScaleInv * click}); dynamicTTM.AdvanceAction(); }, [&](const auto click) { rootWidget.OnMouseEvent( Gui::LeftMouseRelease{guiScaleInv * click}); } ); inputHandler.BindMouse( GLFW_MOUSE_BUTTON_RIGHT, [&](auto click) { rootWidget.OnMouseEvent( Gui::RightMousePress{guiScaleInv * click}); }, [&](auto click) { rootWidget.OnMouseEvent( Gui::RightMouseRelease{guiScaleInv * click}); } ); inputHandler.BindMouseMotion( [&](auto pos) { rootWidget.OnMouseEvent( Gui::MouseMove{guiScaleInv * pos}); } ); // Graphics stuff glfwSetInputMode(window.get(), GLFW_CURSOR, GLFW_CURSOR_HIDDEN); glEnable(GL_MULTISAMPLE); glDisable(GL_DEPTH_TEST); glDepthFunc(GL_LESS); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); double currentTime = 0; double lastTime = 0; do { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); currentTime = glfwGetTime(); animatorStore.OnTimeDelta(currentTime - lastTime); lastTime = currentTime; guiRenderer.RenderGui(&rootWidget); glfwSwapBuffers(window.get()); glfwPollEvents(); } while (glfwGetKey(window.get(), GLFW_KEY_ESCAPE) != GLFW_PRESS && glfwWindowShouldClose(window.get()) == 0); ImguiWrapper::Shutdown(); return 0; }
4,543
C++
.cpp
139
25.834532
77
0.640258
xavieran/BaKGL
39
2
32
GPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,426
display_startup_files.cpp
xavieran_BaKGL/app/display_startup_files.cpp
#include "bak/startupFiles.hpp" #include "bak/combat.hpp" #include "com/logger.hpp" int main(int argc, char** argv) { const auto& logger = Logging::LogState::GetLogger("main"); Logging::LogState::SetLevel(Logging::LogLevel::Debug); Logging::LogState::SetLogTime(false); logger.Info() << "CHAPX.DAT\n"; for (unsigned i = 1; i < 10; i++) { auto chapData = BAK::LoadChapterStartLocation(BAK::Chapter{i}); logger.Info() << "Chapter " << i << " data: " << chapData.mLocation << " ml: " << chapData.mMapLocation << "\n"; } logger.Info() << "FILTER.DAT\n"; BAK::LoadFilter(); logger.Info() << "DETECT.DAT\n"; BAK::LoadDetect(); logger.Info() << "Z00DEF.DAT\n"; for (unsigned i = 1; i < 13; i++) { BAK::LoadZoneDefDat(BAK::ZoneNumber{i}); } logger.Info() << "Z00MAP.DAT\n"; for (unsigned i = 1; i < 13; i++) { BAK::LoadZoneMap(BAK::ZoneNumber{i}); } logger.Info() << "Z00.DAT\n"; for (unsigned i = 1; i < 13; i++) { BAK::LoadZoneDat(BAK::ZoneNumber{i}); } BAK::LoadP1Dat(); return 0; }
1,141
C++
.cpp
37
25.432432
76
0.574954
xavieran/BaKGL
39
2
32
GPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,428
display_gds.cpp
xavieran_BaKGL/app/display_gds.cpp
#include "bak/hotspot.hpp" #include "bak/dialog.hpp" #include "com/logger.hpp" #include "bak/file/fileBuffer.hpp" int main(int argc, char** argv) { const auto& logger = Logging::LogState::GetLogger("main"); Logging::LogState::SetLevel(Logging::LogLevel::Spam); Logging::LogState::Disable("DialogStore"); Logging::LogState::Disable("LoadScenes"); Logging::LogState::Disable("LoadSceneIndices"); Logging::LogState::Disable("FileDataProvider"); Logging::LogState::Disable("PackedFileDataProvider"); Logging::LogState::Disable("CreateFileBuffer"); std::string gdsFile{argv[1]}; logger.Info() << "Loading gds:" << gdsFile << std::endl; auto fb = BAK::FileBufferFactory::Get().Get().CreateDataBuffer(gdsFile); BAK::SceneHotspots sceneHotspots{std::move(fb)}; const auto& dialog = BAK::DialogStore::Get(); if (sceneHotspots.mFlavourText != 0) { logger.Info() << dialog.GetFirstText(dialog.GetSnippet(BAK::KeyTarget{sceneHotspots.mFlavourText})) << std::endl; } return 0; }
1,054
C++
.cpp
25
37.64
121
0.705998
xavieran/BaKGL
39
2
32
GPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,429
display_fo.cpp
xavieran_BaKGL/app/display_fo.cpp
#include "bak/fixedObject.hpp" #include "com/logger.hpp" int main(int argc, char** argv) { const auto& logger = Logging::LogState::GetLogger("main"); Logging::LogState::SetLevel(Logging::LogLevel::Spam); Logging::LogState::Disable("DialogStore"); const auto obj = BAK::LoadFixedObjects(1); return 0; }
331
C++
.cpp
10
29.2
62
0.711538
xavieran/BaKGL
39
2
32
GPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,430
instancing.cpp
xavieran_BaKGL/app/instancing.cpp
#include "com/logger.hpp" #include "com/ostream.hpp" #include "graphics/inputHandler.hpp" #include "graphics/glm.hpp" #include "graphics/glfw.hpp" #include "graphics/guiRenderer.hpp" #include "gui/window.hpp" #include "gui/icons.hpp" #include "imgui/imguiWrapper.hpp" #include <GLFW/glfw3.h> #include <glm/glm.hpp> #include <memory> #include <sstream> int main(int argc, char** argv) { const auto& logger = Logging::LogState::GetLogger("main"); Logging::LogState::SetLevel(Logging::LogLevel::Debug); auto guiScalar = 4.0f; auto width = 1600.0f; auto height = 1000.0f; auto window = Graphics::MakeGlfwWindow( height, width, "BMX Explorer"); glViewport(0, 0, width, height); ImguiWrapper::Initialise(window.get()); // Dark blue background glClearColor(0.15f, 0.31f, 0.36f, 0.0f); auto spriteManager = Graphics::SpriteManager{}; auto guiRenderer = Graphics::GuiRenderer{ width, height, guiScalar, spriteManager}; auto root = Gui::Window{ spriteManager, width / guiScalar, height / guiScalar}; auto icons = Gui::Icons{spriteManager}; unsigned iconI = 0; auto picture = Gui::Widget{ Gui::ImageTag{}, Graphics::SpriteSheetIndex{1}, Graphics::TextureIndex{0}, glm::vec2{0,0}, glm::vec2{100,100}, true}; root.AddChildBack(&picture); root.HideCursor(); auto vao = Graphics::VertexArrayObject{}; vao.BindGL(); const auto& ss = spriteManager.GetSpriteSheet(Graphics::SpriteSheetIndex{1}); auto buffers = Graphics::GLBuffers{}; logger.Debug() << "Made buffers\n"; // vertices std::vector<glm::vec3> vertices{}; { const auto [o, l] = ss.mObjects.GetObject(0); for (unsigned i = 0; i < l; i++) vertices.emplace_back(ss.mObjects.mVertices[i]); } logger.Debug() << "Vertices: " << vertices << "\n"; // indices std::vector<unsigned> indices{}; { const auto [o, l] = ss.mObjects.GetObject(0); for (unsigned i = 0; i < l; i++) indices.emplace_back(ss.mObjects.mIndices[i]); } logger.Debug() << "Indices: " << indices << "\n"; // view matrix const auto viewMatrix = guiRenderer.mCamera.mViewMatrix; unsigned objs = 20; // Things that are differing // model matrices auto transform = std::vector<glm::vec4>{}; { auto pos = glm::vec2{0, 60}; for (unsigned i = 0; i < ss.mSpriteDimensions.size(); i++) { const auto dim1 = ss.GetDimensions(i % objs); transform.emplace_back(guiScalar * glm::vec4{pos.x, pos.y, dim1.x, dim1.y}); pos += glm::vec2{dim1.x / 2, 0}; } } // texture coords auto textureCoords = std::vector<glm::vec4>{}; for (auto i = ss.mObjects.mTextureCoords.begin() + 6; i != ss.mObjects.mTextureCoords.end(); i++) textureCoords.emplace_back(glm::vec4{i->x, i->y, i->z, 0}); // color modes auto colorModes = std::vector<unsigned>{}; for (unsigned i = 0; i < ss.mSpriteDimensions.size(); i++) colorModes.emplace_back(0); // colors auto colors = std::vector<glm::vec4>{}; for (unsigned i = 0; i < ss.mSpriteDimensions.size(); i++) colors.emplace_back(glm::vec4{1}); auto params = std::vector<glm::ivec4>{}; for (unsigned i = 0; i < ss.mSpriteDimensions.size(); i++) params.emplace_back(glm::ivec4{0, i % objs, i, 0}); logger.Debug() << " " << vertices.size() << " " << textureCoords.size() << " " << " " << colorModes.size() << " "<< colors.size() << " " << transform.size() << " " << ss.mSpriteDimensions.size() << "\n"; using namespace Graphics; buffers.AddStaticArrayBuffer<glm::vec3>("vertex", GLLocation{0}); buffers.AddStaticArrayBuffer<glm::vec4>("color", GLLocation{1}); buffers.AddStaticArrayBuffer<glm::vec4>("transform", GLLocation{2}); buffers.AddStaticArrayBuffer<glm::vec4>("params", GLLocation{3}); buffers.AddElementBuffer("elements"); buffers.AddTextureBuffer("textureCoords"); buffers.LoadBufferDataGL("vertex", vertices); buffers.LoadBufferDataGL("color", colors); buffers.LoadBufferDataGL("transform", transform); // pack depth with color mode and texcoord buffers.LoadBufferDataGL("params", params); GLuint tbo; glGenBuffers(1, &tbo); glBindBuffer(GL_TEXTURE_BUFFER, tbo); glBufferData( GL_TEXTURE_BUFFER, textureCoords.size() * sizeof(glm::vec4), &textureCoords.front(), GL_STATIC_DRAW); buffers.LoadBufferDataGL("elements", indices); buffers.LoadBufferDataGL("textureCoords", textureCoords); GLuint tbo_tex; glGenTextures(1, &tbo_tex); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_BUFFER, tbo_tex); glTexBuffer(GL_TEXTURE_BUFFER, GL_RGBA32F, buffers.GetGLBuffer("textureCoords").mBuffer.mValue); glBindBuffer(GL_TEXTURE_BUFFER, 0); buffers.SetAttribDivisor("vertex", 0); buffers.SetAttribDivisor("color", 1); buffers.SetAttribDivisor("transform", 1); buffers.SetAttribDivisor("params", 1); buffers.BindArraysGL(); auto shaderProgram = ShaderProgram{ "instance.vert.glsl", //"geometry.glsl", "instance.frag.glsl"}.Compile(); Graphics::InputHandler inputHandler{}; Graphics::InputHandler::BindMouseToWindow(window.get(), inputHandler); Graphics::InputHandler::BindKeyboardToWindow(window.get(), inputHandler); bool useOriginal = true; inputHandler.Bind(GLFW_KEY_K, [&]{ useOriginal = !useOriginal; }); unsigned k = 0; inputHandler.Bind(GLFW_KEY_R, [&]{ auto params = std::vector<glm::ivec4>{}; for (unsigned i = k++; i < ss.mSpriteDimensions.size(); i++) params.emplace_back(glm::ivec4{0, i % objs, i, 0}); buffers.LoadBufferDataGL("params", params); }); inputHandler.Bind(GLFW_KEY_RIGHT, [&]{ iconI++; picture.SetTexture(Graphics::TextureIndex{iconI}); logger.Debug() << "Pic: " << picture << "\n"; }); inputHandler.Bind(GLFW_KEY_LEFT, [&]{ iconI--; const auto& [ss, ti, dims] = icons.GetInventoryLockIcon(iconI); picture.SetSpriteSheet(ss); picture.SetTexture(ti); picture.SetDimensions(dims); logger.Debug() << "Pic: " << picture << "\n"; }); inputHandler.BindMouse(GLFW_MOUSE_BUTTON_LEFT, [&](auto p) { logger.Debug() << p << "\n"; }, [](auto){}); double currentTime = 0; double lastTime = 0; float deltaTime = 0; glfwSetCursorPos(window.get(), width / 2, height / 2); glEnable(GL_MULTISAMPLE); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LESS); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); double pointerPosX, pointerPosY; double acc = 0; unsigned i = 0; do { currentTime = glfwGetTime(); deltaTime = float(currentTime - lastTime); acc += deltaTime; if (acc > .2) { i = (i + 1) % 20; acc = 0; } lastTime = currentTime; glfwPollEvents(); glfwGetCursorPos(window.get(), &pointerPosX, &pointerPosY); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // { *** Draw 2D GUI *** if (useOriginal) { guiRenderer.RenderGui(&root); } else { vao.BindGL(); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_BUFFER, tbo_tex); shaderProgram.UseProgramGL(); glUniform1i(shaderProgram.GetUniformLocation("texCoords"), 1); glActiveTexture(GL_TEXTURE0); ss.mTextureBuffer.BindGL(); // bind tex... shaderProgram.SetUniform( shaderProgram.GetUniformLocation("V"), viewMatrix); shaderProgram.SetUniform( shaderProgram.GetUniformLocation("texture0"), 0); glDrawElementsInstanced(GL_TRIANGLES, 6, GL_UNSIGNED_INT, (void*) 0, objs); } glfwSwapBuffers(window.get()); } while (glfwGetKey(window.get(), GLFW_KEY_ESCAPE) != GLFW_PRESS && glfwWindowShouldClose(window.get()) == 0); ImguiWrapper::Shutdown(); glfwTerminate(); return 0; }
8,454
C++
.cpp
225
30.377778
133
0.620402
xavieran/BaKGL
39
2
32
GPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,431
display_tile.cpp
xavieran_BaKGL/app/display_tile.cpp
#include "com/logger.hpp" #include "bak/encounter/encounter.hpp" #include "bak/zoneReference.hpp" #include "bak/palette.hpp" #include "bak/worldFactory.hpp" #include "graphics/glm.hpp" int main(int argc, char** argv) { const auto& logger = Logging::LogState::GetLogger("main"); Logging::LogState::SetLevel(Logging::LogLevel::Debug); if (argc != 4) { logger.Info() << "usage: display_tile <zone> <x> <y>" << std::endl; return 1; } auto zoneLabel = BAK::ZoneLabel{argv[1]}; std::string tileX {argv[2]}; std::string tileY {argv[3]}; unsigned x = std::atoi(tileX.c_str()); unsigned y = std::atoi(tileY.c_str()); const auto pal = BAK::Palette{zoneLabel.GetPalette()}; auto textures = BAK::ZoneTextureStore{zoneLabel, pal}; auto zoneItems = BAK::ZoneItemStore{zoneLabel, textures}; const auto tiles = BAK::LoadZoneRef(zoneLabel.GetZoneReference()); unsigned i; for (i = 0; i < tiles.size(); i++) if (tiles[i].x == x && tiles[i].y == y) break; logger.Info() << "Loading world tile:" << tileX << tileY << std::endl; const auto ef = BAK::Encounter::EncounterFactory{}; auto world = BAK::World{zoneItems, ef, x, y, i}; for (const auto& item : world.GetItems()) { const auto& name = item.GetZoneItem().GetName(); if (name.substr(0, 4) == "tree") continue; logger.Info() << "Item: " << name << " loc: " << item.GetLocation() << std::endl; } constexpr auto chapter = 1; logger.Info() << "Encounters: " << world.GetEncounters(BAK::Chapter{chapter}).size() << "\n"; for (const auto& encounter : world.GetEncounters(BAK::Chapter{chapter})) { logger.Info() << "Encounter: " << encounter << "\n"; } return 0; }
1,793
C++
.cpp
45
34.4
97
0.619792
xavieran/BaKGL
39
2
32
GPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,432
decomp_ttm.cpp
xavieran_BaKGL/app/decomp_ttm.cpp
#include "bak/scene.hpp" #include "com/logger.hpp" #include "bak/file/fileBuffer.hpp" int main(int argc, char** argv) { const auto& logger = Logging::LogState::GetLogger("main"); Logging::LogState::SetLevel(Logging::LogLevel::Debug); if (argc < 2) { std::cerr << "No arguments provided!\nUsage: " << argv[0] << " TTM\n"; return -1; } std::string ttmFile{argv[1]}; auto fb = BAK::FileBufferFactory::Get().CreateDataBuffer(ttmFile); auto newFB = BAK::DecompressTTM(fb); auto saveFile = std::ofstream{ "NEW.TTM", std::ios::binary | std::ios::out}; newFB.Save(saveFile); return 0; }
680
C++
.cpp
22
25.318182
70
0.621705
xavieran/BaKGL
39
2
32
GPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,433
display_traps.cpp
xavieran_BaKGL/app/display_traps.cpp
#include "bak/trap.hpp" #include "com/logger.hpp" int main(int argc, char** argv) { const auto& logger = Logging::LogState::GetLogger("main"); Logging::LogState::SetLevel(Logging::LogLevel::Debug); logger.Info() << "Loading Traps\n"; BAK::LoadTraps(); return 0; }
293
C++
.cpp
10
25.4
62
0.678832
xavieran/BaKGL
39
2
32
GPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,434
display_dialog.cpp
xavieran_BaKGL/app/display_dialog.cpp
#include "bak/dialog.hpp" #include "com/visit.hpp" #include "com/logger.hpp" unsigned GetInput() { std::string in; std::getline(std::cin, in); std::stringstream ss; std::uint32_t input; ss << in; ss >> input; return input; } int main(int argc, char** argv) { const auto& logger = Logging::LogState::GetLogger("main"); Logging::LogState::SetLevel(Logging::LogLevel::Spam); Logging::LogState::SetLogTime(false); BAK::Keywords keywords{}; const auto& dialog = BAK::DialogStore::Get(); //dialog.ShowAllDialogs(); std::uint32_t key; std::stringstream ss{}; ss << std::hex << argv[1]; ss >> key; BAK::Target current; current = BAK::KeyTarget{key}; BAK::DialogSnippet const* dialogSnippet; try { dialogSnippet = &dialog.GetSnippet(current); } catch (const std::runtime_error& e) { logger.Error() << "Could not find snippet with target:" << current << "\n"; return -1; } bool good = true; while (good) { std::cout << "---------------------------------------- \n"; std::stringstream ss; ss << "Current: " << current; if (std::holds_alternative<BAK::KeyTarget>(current)) ss << " (" << dialog.GetTarget(std::get<BAK::KeyTarget>(current)) << ")"; ss << "\n"; logger.Info() << ss.str(); logger.Info() << "Snippet: " << *dialogSnippet << "\n"; unsigned i = 0; for (const auto& c : dialogSnippet->GetChoices()) std::cout << c << " (" << i++ << ")\n"; std::cout << ">>> "; auto choice = GetInput(); if (choice > dialogSnippet->GetChoices().size()) return 0; auto next = dialogSnippet->GetChoices()[choice]; current = next.mTarget; if (evaluate_if<BAK::KeyTarget>(current, [](const auto& current){ return current == BAK::KeyTarget{0}; })) { return 0; } dialogSnippet = &dialog.GetSnippet(current); } return 0; }
2,057
C++
.cpp
65
25.076923
114
0.556853
xavieran/BaKGL
39
2
32
GPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,435
display_ramp.cpp
xavieran_BaKGL/app/display_ramp.cpp
#include "bak/ramp.hpp" #include "bak/fileBufferFactory.hpp" #include "com/logger.hpp" int main(int argc, char** argv) { const auto& logger = Logging::LogState::GetLogger("main"); Logging::LogState::SetLevel(Logging::LogLevel::Debug); Logging::LogState::SetLogTime(false); auto file = std::string(argv[1]); auto fb = BAK::FileBufferFactory::Get().CreateDataBuffer(file); auto ramp = BAK::LoadRamp(fb); logger.Info() << ramp << "\n"; return 0; }
480
C++
.cpp
14
30.785714
67
0.686825
xavieran/BaKGL
39
2
32
GPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,436
dynamicTTM.cpp
xavieran_BaKGL/gui/dynamicTTM.cpp
#include "gui/dynamicTTM.hpp" #include "audio/audio.hpp" #include "bak/dialogAction.hpp" #include "gui/backgrounds.hpp" #include "gui/colors.hpp" #include "gui/callbackDelay.hpp" #include "gui/fontManager.hpp" #include "bak/dialogSources.hpp" #include "bak/imageStore.hpp" #include "bak/screen.hpp" #include "bak/textureFactory.hpp" #include "bak/ttmRenderer.hpp" #include "bak/dialog.hpp" #include "com/assert.hpp" #include "com/logger.hpp" #include "graphics/types.hpp" namespace Gui { DynamicTTM::DynamicTTM( Graphics::SpriteManager& spriteManager, AnimatorStore& animatorStore, const Font& font, const Backgrounds& backgrounds, std::function<void()>&& sceneFinished, std::function<void(unsigned)>&& displayBook) : mSpriteManager{spriteManager}, mAnimatorStore{animatorStore}, mFont{font}, mSceneFrame{ Graphics::DrawMode::Rect, Graphics::SpriteSheetIndex{0}, Graphics::TextureIndex{0}, Graphics::ColorMode::SolidColor, glm::vec4{0}, glm::vec2{0}, glm::vec2{1}, false }, mDialogBackground{ Graphics::DrawMode::Sprite, backgrounds.GetSpriteSheet(), backgrounds.GetScreen("DIALOG.SCX"), Graphics::ColorMode::Texture, glm::vec4{1}, glm::vec2{0}, glm::vec2{320, 200}, true }, mRenderedElements{ Graphics::DrawMode::Rect, Graphics::SpriteSheetIndex{0}, Graphics::TextureIndex{0}, Graphics::ColorMode::SolidColor, glm::vec4{0}, glm::vec2{0}, glm::vec2{1}, false }, mLowerTextBox{ glm::vec2{15, 125}, glm::vec2{285, 66} }, mPopup{ glm::vec2{}, glm::vec2{}, Color::buttonBackground, Color::buttonHighlight, Color::buttonShadow, Color::black }, mPopupText{ glm::vec2{}, glm::vec2{} }, mSceneElements{}, mRunner{}, mRenderedFramesSheet{}, mSceneFinished{std::move(sceneFinished)}, mDisplayBook{std::move(displayBook)}, mLogger{Logging::LogState::GetLogger("Gui::DynamicTTM")} { mPopup.AddChildBack(&mPopupText); mSceneFrame.AddChildBack(&mDialogBackground); mSceneFrame.AddChildBack(&mRenderedElements); } void DynamicTTM::BeginScene( std::string adsFile, std::string ttmFile) { mLogger.Debug() << "Loading ADS/TTM: " << adsFile << " " << ttmFile << "\n"; BAK::TTMRenderer renderer(adsFile, ttmFile); mRenderedFrames = renderer.RenderTTM(); mRenderedFramesSheet = mSpriteManager.AddTemporarySpriteSheet(); mCurrentRenderedFrame = 0; mSpriteManager.GetSpriteSheet(mRenderedFramesSheet->mSpriteSheet).LoadTexturesGL(mRenderedFrames); mSceneElements.clear(); mSceneElements.emplace_back( Graphics::DrawMode::Sprite, mRenderedFramesSheet->mSpriteSheet, Graphics::TextureIndex{0}, Graphics::ColorMode::Texture, glm::vec4{1}, glm::vec2{0}, glm::vec2{320, 200}, false ); mRenderedElements.ClearChildren(); for (auto& element : mSceneElements) { mRenderedElements.AddChildBack(&element); } mDelaying = false; mDelay = 0; mRunner.LoadTTM(adsFile, ttmFile); ClearText(); } bool DynamicTTM::AdvanceAction() { if (mDelaying) return false; auto actionOpt = mRunner.GetNextAction(); if (!actionOpt) { mSceneFinished(); return true; } auto action = *actionOpt; mLogger.Debug() << "This action: " << action << "\n"; bool waitForClick = false; std::visit( overloaded{ [&](const BAK::Delay& delay){ mDelay = static_cast<double>(delay.mDelayMs) / 1000.; }, [&](const BAK::ShowDialog& dialog){ waitForClick = RenderDialog(dialog); }, [&](const BAK::Update& sr){ mSceneElements.back().SetTexture( Graphics::TextureIndex{mCurrentRenderedFrame++}); }, [&](const BAK::Purge&){ assert(false); }, [&](const BAK::PlaySoundS& sound){ if (sound.mSoundIndex < 255) { AudioA::AudioManager::Get().PlaySound(AudioA::SoundIndex{sound.mSoundIndex}); } else { AudioA::AudioManager::Get().ChangeMusicTrack(AudioA::MusicIndex{sound.mSoundIndex}); } }, [&](const BAK::GotoTag& sa){ assert(false); }, [&](const auto&){} }, action ); if (!waitForClick) { mDelaying = true; mAnimatorStore.AddAnimator(std::make_unique<CallbackDelay>( [&](){ mDelaying = false; AdvanceAction(); }, mDelay)); } return false; } bool DynamicTTM::RenderDialog(const BAK::ShowDialog& dialog) { // mDialogType == 5 - display dialog using RunDialog (i.e. No actor names, no default bold) // mDialogType == 1 and 4 - similar to above... not sure the difference // mDialogType == 3 - same as above - no wait // mDialogType == 0 - the usual method if (dialog.mDialogType == 2) { mDisplayBook(dialog.mDialogKey); return true; } if (dialog.mDialogType != 0xff && dialog.mDialogKey != 0 && dialog.mDialogKey != 0xff) { const auto& snippet = BAK::DialogStore::Get().GetSnippet( BAK::DialogSources::GetTTMDialogKey(dialog.mDialogKey)); auto popup = snippet.GetPopup(); mLogger.Debug() << "Show snippet;" << snippet << "\n"; if (popup) { mPopup.SetPosition(popup->mPos); mPopup.SetDimensions(popup->mDims); mPopupText.SetPosition(glm::vec2{1}); mPopupText.SetDimensions(popup->mDims); mPopupText.SetText(mFont, snippet.GetText(), true, true); mLowerTextBox.ClearChildren(); if (!mSceneFrame.HaveChild(&mPopup)) { mSceneFrame.AddChildBack(&mPopup); } } else { mLowerTextBox.SetText(mFont, snippet.GetText()); mPopupText.ClearChildren(); if (!mSceneFrame.HaveChild(&mLowerTextBox)) { mSceneFrame.AddChildBack(&mLowerTextBox); } } return true; } else { ClearText(); } return false; } void DynamicTTM::ClearText() { mPopupText.ClearChildren(); mLowerTextBox.ClearChildren(); if (mSceneFrame.HaveChild(&mPopup)) { mSceneFrame.RemoveChild(&mPopup); } if (mSceneFrame.HaveChild(&mLowerTextBox)) { mSceneFrame.RemoveChild(&mLowerTextBox); } } Widget* DynamicTTM::GetScene() { return &mSceneFrame; } }
6,975
C++
.cpp
237
21.827004
104
0.598778
xavieran/BaKGL
39
2
32
GPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,437
gdsScene.cpp
xavieran_BaKGL/gui/gdsScene.cpp
#include "gui/gdsScene.hpp" #include "audio/audio.hpp" #include "bak/bard.hpp" #include "bak/dialogSources.hpp" #include "bak/fileBufferFactory.hpp" #include "bak/money.hpp" #include "bak/temple.hpp" #include "bak/state/temple.hpp" #include "bak/state/event.hpp" #include "com/assert.hpp" namespace Gui { GDSScene::GDSScene( Cursor& cursor, BAK::HotspotRef hotspotRef, Graphics::SpriteManager& spriteManager, const Actors& actors, const Backgrounds& backgrounds, const Font& font, BAK::GameState& gameState, IGuiManager& guiManager) : Widget{ Graphics::DrawMode::Sprite, spriteManager.AddSpriteSheet(), Graphics::TextureIndex{0}, Graphics::ColorMode::Texture, glm::vec4{1}, glm::vec2{0}, glm::vec2{1}, false }, mSpriteSheet{spriteManager.AddTemporarySpriteSheet()}, mFont{font}, mReference{hotspotRef}, mGameState{gameState}, mSceneHotspots{ BAK::FileBufferFactory::Get().CreateDataBuffer( mReference.ToFilename())}, mFlavourText{BAK::KeyTarget{0x0}}, mSpriteManager{spriteManager}, // bitofa hack - all gds scenes have such a frame mFrame{ Graphics::DrawMode::Rect, mSpriteSheet->mSpriteSheet, Graphics::TextureIndex{0}, Graphics::ColorMode::SolidColor, Color::frameMaroon, glm::vec2{14, 10}, glm::vec2{291, 103}, false}, mStaticTTMs{}, mHotspots{}, mHotspotClicked{}, mCursor{cursor}, mGuiManager{guiManager}, mDialogDisplay{ glm::vec2{0, 0}, glm::vec2{320, 240}, actors, backgrounds, font, gameState}, mPendingAction{}, mPendingGoto{}, mKickedOut{false}, mTemple{ mGameState, mGuiManager }, mRepair{ mGameState, mGuiManager }, mLogger{Logging::LogState::GetLogger("Gui::GDSScene")} { SetSpriteSheet(mSpriteSheet->mSpriteSheet); auto textures = Graphics::TextureStore{}; BAK::TextureFactory::AddScreenToTextureStore( textures, "DIALOG.SCX", "OPTIONS.PAL"); const auto dims = textures.GetTexture(0).GetDims(); mSpriteManager .GetSpriteSheet(mSpriteSheet->mSpriteSheet) .LoadTexturesGL(textures); SetDimensions(dims); auto fb = BAK::FileBufferFactory::Get().CreateDataBuffer(mReference.ToFilename()); mFlavourText = BAK::KeyTarget{mSceneHotspots.mFlavourText}; if (mFlavourText == BAK::KeyTarget{0x10000}) mFlavourText = BAK::KeyTarget{0}; // Needed for repair shops... auto* container = mGameState.GetContainerForGDSScene(mReference); if (container && container->IsShop()) { auto& shopStats = container->GetShop(); mGameState.SetShopType_7542(shopStats.mRepairTypes); } const auto& scene1 = mSceneHotspots.GetScene( mSceneHotspots.mSceneIndex1, mGameState); const auto& scene2 = mSceneHotspots.GetScene( mSceneHotspots.mSceneIndex2, mGameState); // Unlikely we ever nest this deep mStaticTTMs.reserve(mMaxSceneNesting); mStaticTTMs.emplace_back( mSpriteManager, scene1, scene2); AddChildBack(&mFrame); mFrame.SetInactive(); // Want our refs to be stable.. mHotspots.reserve(mSceneHotspots.mHotspots.size()); mHotspotClicked.reserve(mSceneHotspots.mHotspots.size()); for (unsigned i = 0; i < mSceneHotspots.mHotspots.size(); i++) { mHotspotClicked.emplace_back(false); auto& hs = mSceneHotspots.mHotspots[i]; const auto isActive = hs.IsActive(mGameState); mLogger.Debug() << "Checked HS: " << hs.mHotspot << " " << isActive << "\n"; if (isActive) { mHotspots.emplace_back( [this, hs, i](){ mLogger.Debug() << "Clicked : " << hs.mHotspot << std::endl; const bool clicked = mHotspotClicked[i]; mHotspotClicked[i] = true; HandleHotspotLeftClicked(hs, clicked); }, [this, hs](){ HandleHotspotRightClicked(hs); }, cursor, mFont, hs.mTopLeft, hs.mDimensions, hs.mHotspot, hs.mKeyword - 1 // cursor index ); AddChildBack(&mHotspots.back()); } } DisplayNPCBackground(); if (mFlavourText != BAK::KeyTarget{0}) mDialogDisplay.ShowFlavourText(mFlavourText); AddChildBack(&mDialogDisplay); mLogger.Debug() << "Constructed @" << std::hex << this << std::dec << "\n"; } void GDSScene::EnterGDSScene() { std::optional<BAK::Hotspot> evaluateImmediately{}; for (const auto hotspot : mSceneHotspots.mHotspots) { if (hotspot.IsActive(mGameState) && hotspot.mAction == BAK::HotspotAction::TELEPORT) { assert(mSceneHotspots.GetTempleNumber()); mGameState.Apply(BAK::State::SetTempleSeen, *mSceneHotspots.GetTempleNumber()); } if (hotspot.IsActive(mGameState) && hotspot.EvaluateImmediately()) { assert(!evaluateImmediately); evaluateImmediately = hotspot; } } mPendingAction.reset(); mPendingGoto.reset(); if (evaluateImmediately) { HandleHotspotLeftClicked(*evaluateImmediately, false); } } void GDSScene::DisplayNPCBackground() { mFrame.ClearChildren(); ASSERT(mStaticTTMs.size() > 0); mFrame.AddChildBack(mStaticTTMs.back().GetScene()); } void GDSScene::DisplayPlayerBackground() { mFrame.ClearChildren(); ASSERT(mStaticTTMs.size() > 0); mFrame.AddChildBack(mStaticTTMs.back().GetBackground()); } void GDSScene::HandleHotspotLeftClicked(const BAK::Hotspot& hotspot, bool hotspotClicked) { mLogger.Debug() << "Hotspot: " << hotspot << "\n"; mGameState.SetItemValue(BAK::Royals{0}); mPendingAction = hotspot.mAction; if (hotspot.mAction == BAK::HotspotAction::GOTO) { auto hotspotRef = mReference; hotspotRef.mGdsChar = BAK::MakeHotspotChar(hotspot.mActionArg1); mPendingGoto = hotspotRef; } if ((hotspot.mActionArg3 != 0 && hotspot.mActionArg3 != 0x10000) && hotspot.mAction != BAK::HotspotAction::TEMPLE) { if (hotspot.mActionArg2 != 0) { const auto& scene1 = mSceneHotspots.GetScene( mSceneHotspots.mSceneIndex1, mGameState); const auto& scene2 = mSceneHotspots.GetScene( hotspot.mActionArg2, mGameState); AddStaticTTM(scene1, scene2); } mGameState.SetDialogContext_7530(hotspotClicked); mGameState.SetBardReward_754d(0); auto* container = mGameState.GetContainerForGDSScene(mReference); if (container && container->IsShop()) { mGameState.SetBardReward_754d(container->GetShop().mBardingReward); mGameState.SetShopType_7542(container->GetShop().mRepairTypes); } StartDialog(BAK::KeyTarget{hotspot.mActionArg3}, false); } else if (hotspot.mAction == BAK::HotspotAction::TEMPLE) { DoTemple(BAK::KeyTarget{hotspot.mActionArg3}); mPendingAction.reset(); } else if (hotspot.mAction == BAK::HotspotAction::TELEPORT) { assert(mSceneHotspots.GetTempleNumber()); if (mGameState.GetChapter() == BAK::Chapter{6} && *mSceneHotspots.GetTempleNumber() == BAK::Temple::sChapelOfIshap && !mGameState.ReadEventBool(BAK::GameData::sPantathiansEventFlag)) { mGuiManager.StartDialog(BAK::DialogSources::mTeleportDialogTeleportBlockedMalacsCrossSource, false, false, this); mPendingAction.reset(); } else { StartDialog(BAK::DialogSources::mTeleportDialogIntro, false); } } else { EvaluateHotspotAction(); } } void GDSScene::DialogFinished(const std::optional<BAK::ChoiceIndex>& choice) { if (mKickedOut) { mPendingAction = BAK::HotspotAction::EXIT; mKickedOut = false; } if (mBarding) { AudioA::AudioManager::Get().PopTrack(); mBarding = false; } if (mFlavourText != BAK::KeyTarget{0}) mDialogDisplay.ShowFlavourText(mFlavourText); if (mStaticTTMs.size() > 1) { for (unsigned i = 1; i < mStaticTTMs.size(); i++) { mStaticTTMs.pop_back(); } } DisplayNPCBackground(); if (!mPendingAction) { mLogger.Debug() << "No pending action at end of dialog, not evaluating further\n"; return; } const auto index = mGameState.GetEndOfDialogState() + 5; // After dialog finished... switch (index) { case 4: mPendingAction = BAK::HotspotAction::UNKNOWN_0; break; case 3: mPendingAction = BAK::HotspotAction::BARMAID; break; case 2: mPendingAction = BAK::HotspotAction::INN; break; case 1: mPendingAction = BAK::HotspotAction::EXIT; break; case 0: mPendingAction = BAK::HotspotAction::REPAIR_2; break; default: break; } auto* container = mGameState.GetContainerForGDSScene(mReference); if (container && container->IsShop()) { if (mGameState.GetBardReward_754d() > 0xfa) { mGameState.SetBardReward_754d(0xfa); } container->GetShop().mBardingReward = mGameState.GetBardReward_754d(); } mGameState.SetBardReward_754d(0); EvaluateHotspotAction(); } void GDSScene::AddStaticTTM(BAK::Scene scene1, BAK::Scene scene2) { ASSERT(mStaticTTMs.size () < mMaxSceneNesting); mLogger.Debug() << __FUNCTION__ << " " << scene1 << " --- " << scene2 << " \n"; mStaticTTMs.emplace_back( mSpriteManager, scene1, scene2); DisplayNPCBackground(); } void GDSScene::EvaluateHotspotAction() { if (!mPendingAction) { mLogger.Debug() << "No action present, not evaluating\n"; return; } if (*mPendingAction == BAK::HotspotAction::SHOP) { EnterContainer(); } else if (*mPendingAction == BAK::HotspotAction::CONTAINER) { EnterContainer(); } else if (*mPendingAction == BAK::HotspotAction::LUTE) { DoBard(); } else if (*mPendingAction == BAK::HotspotAction::BARMAID) { EnterContainer(); } else if (*mPendingAction == BAK::HotspotAction::INN) { if (mGameState.GetChapter() == BAK::Chapter{5}) { auto* container = mGameState.GetContainerForGDSScene(mReference); assert(container && container->IsShop()); // 0xdb1c Eortis/rusalka qeust? if (!mGameState.ReadEventBool(0xdb1c)) { container->GetShop().mInnCost = 0x48; } else { container->GetShop().mInnCost = 0xa; } } DoInn(); } else if (*mPendingAction == BAK::HotspotAction::REPAIR_2 || *mPendingAction == BAK::HotspotAction::REPAIR) { DoRepair(); } else if (*mPendingAction == BAK::HotspotAction::CHAPTER_END) { mCursor.PopCursor(); mGuiManager.DoChapterTransition(); } else if (*mPendingAction == BAK::HotspotAction::TELEPORT) { DoTeleport(); } // this can be set by barding failure else if (*mPendingAction == BAK::HotspotAction::EXIT) { DoExit(); return; } else if (*mPendingAction == BAK::HotspotAction::GOTO) { DoGoto(); } mPendingAction.reset(); } void GDSScene::HandleHotspotRightClicked(const BAK::Hotspot& hotspot) { mLogger.Debug() << "Hotspot: " << hotspot << "\n"; StartDialog(hotspot.mTooltip, true); } void GDSScene::StartDialog(const BAK::Target target, bool isTooltip) { mDialogDisplay.Clear(); mGuiManager.StartDialog(target, isTooltip, false, this); } void GDSScene::EnterContainer() { auto* container = mGameState.GetContainerForGDSScene(mReference); if (container != nullptr) { if (container->IsShop()) { mLogger.Debug() << " EnterContainer: " << container->GetShop() << "\n"; } mGuiManager.ShowContainer(container, BAK::EntityType::BAG); } } void GDSScene::DoInn() { auto* container = mGameState.GetContainerForGDSScene(mReference); assert(container && container->IsShop()); auto& shopStats = container->GetShop(); mGuiManager.ShowCamp(true, &container->GetShop()); } void GDSScene::DoBard() { auto* container = mGameState.GetContainerForGDSScene(mReference); assert(container && container->IsShop()); auto& shopStats = container->GetShop(); const auto [character, skill] = mGameState.GetPartySkill( BAK::SkillType::Barding, true); mGameState.SetActiveCharacter(character); // uncomment this to fix the bug in Tom's Tavern with interaction // between gambling and barding... :) //if (shopStats.mBardingMaxReward != shopStats.mBardingReward) if (shopStats.mBardingReward == 0) { StartDialog(BAK::DialogSources::mBardingAlreadyDone, false); } else { const auto status = BAK::Bard::ClassifyBardAttempt( skill, shopStats.mBardingSkill); switch (status) { case BAK::Bard::BardStatus::Failed: AudioA::AudioManager::Get().ChangeMusicTrack(AudioA::BAD_BARD); break; case BAK::Bard::BardStatus::Poor: AudioA::AudioManager::Get().ChangeMusicTrack(AudioA::POOR_BARD); break; case BAK::Bard::BardStatus::Good: AudioA::AudioManager::Get().ChangeMusicTrack(AudioA::GOOD_BARD); break; case BAK::Bard::BardStatus::Best: AudioA::AudioManager::Get().ChangeMusicTrack(AudioA::BEST_BARD); break; } const auto reward = BAK::Bard::GetReward( status, BAK::Sovereigns{shopStats.mBardingMaxReward}, mGameState.GetChapter()); // this is to ensure that we can rebard if we didn't succeed at first mGameState.SetBardReward_754d(shopStats.mBardingReward); BAK::Bard::ReduceAvailableReward(shopStats, reward); mGameState.GetParty().GainMoney(reward); const auto skillMultiplier = std::invoke([&]{ if (status == BAK::Bard::BardStatus::Failed || status == BAK::Bard::BardStatus::Poor) return 1; else return 2; }); mGameState.GetParty().ImproveSkillForAll( BAK::SkillType::Barding, BAK::SkillChange::ExercisedSkill, skillMultiplier); if (status == BAK::Bard::BardStatus::Failed) mKickedOut = true; mBarding = true; mGameState.SetItemValue(reward); StartDialog(GetDialog(status), false); } } void GDSScene::DoRepair() { auto* container = mGameState.GetContainerForGDSScene(mReference); assert(container && container->IsShop()); mRepair.EnterRepair(container->GetShop()); } void GDSScene::DoTeleport() { // After end of dialog state... if (mGameState.GetMoreThanOneTempleSeen()) { assert(mSceneHotspots.GetTempleNumber()); mGuiManager.ShowTeleport( *mSceneHotspots.GetTempleNumber(), &mGameState.GetContainerForGDSScene(mReference)->GetShop()); } else { StartDialog(BAK::DialogSources::mTeleportDialogNoDestinations, false); } } void GDSScene::DoTemple(BAK::KeyTarget target) { auto* container = mGameState.GetContainerForGDSScene(mReference); ASSERT(container && container->IsShop()); assert(mSceneHotspots.GetTempleNumber()); const auto& scene1 = mSceneHotspots.GetScene( mSceneHotspots.mSceneIndex1, mGameState); const auto& scene2 = mSceneHotspots.GetScene( 3, mGameState); AddStaticTTM(scene1, scene2); mDialogDisplay.Clear(); mTemple.EnterTemple( target, *mSceneHotspots.GetTempleNumber(), container->GetShop(), this); } void GDSScene::DoGoto() { mGuiManager.DoFade(.8, [this, pendingGoto=*mPendingGoto]{ mGuiManager.EnterGDSScene(pendingGoto, []{}); }); mPendingGoto.reset(); } void GDSScene::DoExit() { mGuiManager.ExitGDSScene(); } }
16,533
C++
.cpp
502
25.673307
125
0.634956
xavieran/BaKGL
39
2
32
GPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,438
scene.cpp
xavieran_BaKGL/gui/scene.cpp
#include "gui/scene.hpp" namespace Gui { EnableClipRegion ConvertSceneAction( const BAK::ClipRegion& clip) { const auto width = clip.mBottomRight.x - clip.mTopLeft.x; const auto height = clip.mBottomRight.y - clip.mTopLeft.y; return EnableClipRegion{ glm::vec2{ clip.mTopLeft.x, clip.mTopLeft.y}, glm::vec2{width, height} }; } DisableClipRegion ConvertSceneAction( const BAK::DisableClipRegion&) { return DisableClipRegion{}; } }
504
C++
.cpp
20
20.55
62
0.691023
xavieran/BaKGL
39
2
32
GPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,439
dialogRunner.cpp
xavieran_BaKGL/gui/dialogRunner.cpp
#include "gui/dialogRunner.hpp" #include "audio/audio.hpp" #include "bak/state/dialog.hpp" namespace Gui { DialogRunner::DialogRunner( glm::vec2 pos, glm::vec2 dims, const Actors& actors, const Backgrounds& bgs, const Font& fr, BAK::GameState& gameState, ScreenStack& screenStack, FinishCallback&& finished) : Widget{ RectTag{}, pos, dims, glm::vec4{0}, true }, mScreenStack{screenStack}, mDialogState{false, false, glm::vec2{0}, glm::vec2{0}}, mChoices{ pos, dims, fr, screenStack, [this](auto choice){ MakeChoice(choice); } }, mKeywords{}, mGameState{gameState}, mCenter{160, 112}, mFont{fr}, mActors{actors}, mCurrentTarget{}, mLastChoice{}, mPendingZoneTeleport{}, mTargetStack{}, mStartedMusic{false}, mRemainingText{""}, mTextDims{0}, mDialogDisplay{pos, dims, actors, bgs, fr, gameState}, mFinished{finished}, mDialogScene{nullptr}, mLogger{Logging::LogState::GetLogger("Gui::DialogRunner")} { AddChildBack(&mDialogDisplay); ASSERT(mFinished); } DialogRunner::~DialogRunner() { mLogger.Debug() << "Destroyed: " << this << "\n"; } std::optional<BAK::TeleportIndex> DialogRunner::GetAndResetPendingTeleport() { auto tmp = mPendingZoneTeleport; mPendingZoneTeleport.reset(); return tmp; } void DialogRunner::SetDialogScene(IDialogScene* dialogScene) { mDialogScene = dialogScene; } void DialogRunner::SetInWorldView(bool value) { mInWorldView = value; } bool DialogRunner::IsActive() { return mDialogState.mDialogActive || mDialogState.mTooltipActive; } void DialogRunner::BeginDialog( BAK::Target target, bool isTooltip) { mLastChoice.reset(); ASSERT(!IsActive()); mGameState.SetCharacterTextVariables(); if (isTooltip) mDialogState.ActivateTooltip(); else mDialogState.ActivateDialog(); mTargetStack.push(target); mLogger.Debug() << "BeginDialog" << target << "\n"; ContinueDialogFromStack(); } bool DialogRunner::OnMouseEvent(const MouseEvent& event) { return std::visit(overloaded{ [this](const LeftMousePress& p){ return LeftMousePressed(p.mValue); }, [this](const MouseMove& p){ return MouseMoved(p.mValue); }, [](const auto& p){ return false; } }, event); } bool DialogRunner::LeftMousePressed(glm::vec2) { if (mDialogState.mTooltipActive) { mDialogState.ForceDeactivateTooltip( [this](){ mDialogScene = nullptr; std::invoke(mFinished, GetLastChoice()); }); } else { RunDialog(); } return true; } bool DialogRunner::MouseMoved(glm::vec2 pos) { mDialogState.MouseMoved(pos); mDialogState.DeactivateTooltip( [this](){ mDialogScene = nullptr; std::invoke(mFinished, GetLastChoice()); }); return false; } void DialogRunner::EvaluateSnippetActions() { mLogger.Debug() << "Evaluating actions for " << mCurrentTarget << "\n"; for (const auto& action : GetSnippet().mActions) { std::visit(overloaded{ [&](const BAK::PushNextDialog& push){ mLogger.Debug() << "Pushing: " << push.mTarget << "\n"; mTargetStack.push(push.mTarget); }, [&](const BAK::Teleport& teleport){ mLogger.Debug() << "Teleporting to zoneIndex: " << teleport.mIndex << "\n"; mPendingZoneTeleport = teleport.mIndex; }, [&](const BAK::PlaySound& sound) { try { mLogger.Debug() << "Playing sound: " << sound << "\n"; if (sound.mSoundIndex == 0) { // FIXME: Is this what 0 means? //AudioA::AudioManager::Get().StopMusicTrack(); } else if (sound.mSoundIndex < AudioA::MAX_SOUND) { AudioA::AudioManager::Get().PlaySound(AudioA::SoundIndex{sound.mSoundIndex}); } else if (sound.mSoundIndex >= AudioA::MIN_SONG) { AudioA::AudioManager::Get().ChangeMusicTrack(AudioA::MusicIndex{sound.mSoundIndex}); // FIXME: Do we need a stack here? mStartedMusic = true; } } catch (std::exception& e) { mLogger.Error() << " Playing sound: " << sound << " failed with: " << e.what() << "\n"; } }, [&](const auto& a){ mGameState.EvaluateAction(BAK::DialogAction{action}); }}, action); } // I added this specifically for Navon's dialog. Need to check others // to see if it is correct for those also. if (mGameState.GetEndOfDialogState() == -1) { while (!mTargetStack.empty()) { mTargetStack.pop(); } // Need to force the combat to be evaluated though... } } void DialogRunner::DisplaySnippet() { std::string text{}; if (!mRemainingText.empty()) { text = mRemainingText; } else { text = GetSnippet().GetText(); // Bit hacky: Add an extra line to ensure enough room to // display the query choice if (GetSnippet().IsQueryChoice()) { text += "\n"; } } auto nullDialog = NullDialogScene{}; const auto [textDims, rem] = mDialogDisplay.DisplaySnippet( mDialogScene ? *mDialogScene : nullDialog, GetSnippet(), text, mInWorldView, mDialogState.mMousePos); mTextDims = textDims; mRemainingText = rem; } const BAK::DialogSnippet& DialogRunner::GetSnippet() const { ASSERT(mCurrentTarget); return BAK::DialogStore::Get().GetSnippet(*mCurrentTarget); } std::optional<BAK::Target> DialogRunner::GetNextTarget() { if (!mCurrentTarget) { if (!mTargetStack.empty()) return GetAndPopTargetStack(); else return std::optional<BAK::Target>{}; } const auto& snip = GetSnippet(); if (snip.IsRandomChoice()) { ASSERT(snip.GetChoices().size() > 0); const auto choice = GetRandomNumber(0, snip.GetChoices().size() - 1); return snip.GetChoices()[choice].mTarget; } else if (snip.GetChoices().size() >= 1) { for (const auto& c : snip.GetChoices()) { if (mGameState.EvaluateDialogChoice(c)) return c.mTarget; } } if (!mTargetStack.empty()) { return GetAndPopTargetStack(); } return std::optional<BAK::Target>{}; } void DialogRunner::MakeChoice(BAK::ChoiceIndex choice) { mLogger.Debug() << "Made choice: " << choice << "\n"; mScreenStack.PopScreen(); const auto& choices = GetSnippet().GetChoices(); const auto it = std::find_if(choices.begin(), choices.end(), [choice](const auto& c){ if (std::holds_alternative<BAK::ConversationChoice>(c.mChoice)) return std::get<BAK::ConversationChoice>(c.mChoice).mEventPointer == choice.mValue; else if (std::holds_alternative<BAK::QueryChoice>(c.mChoice)) return std::get<BAK::QueryChoice>(c.mChoice).mQueryIndex == choice.mValue; else return false; }); mLastChoice = choice; if (it == choices.end()) { // usual "Yes/No" dialogs if (choices.size() == 0 || choices.size() == 1) { mLogger.Info() << "Yes|No dialog choice. Player chose: " << mLastChoice << "\n"; } else { // Break out of the question loop ASSERT(!mTargetStack.empty()); mTargetStack.pop(); } } else { evaluate_if<BAK::ConversationChoice>( it->mChoice, [&](const auto& c){ mGameState.Apply(BAK::State::SetConversationItemClicked, c.mEventPointer); }); mTargetStack.push(it->mTarget); } ContinueDialogFromStack(); } void DialogRunner::ShowDialogChoices() { mLogger.Debug() << "DialogChoices: " << GetSnippet() << "\n"; mChoices.SetPosition(glm::vec2{15, 125}); mChoices.SetDimensions(glm::vec2{295, 66}); auto choices = std::vector<std::pair<BAK::ChoiceIndex, std::string>>{}; unsigned i = 0; for (const auto& c : GetSnippet().GetChoices()) { if (std::holds_alternative<BAK::ConversationChoice>(c.mChoice)) { const auto choice = std::get<BAK::ConversationChoice>(c.mChoice); if (mGameState.CheckConversationItemAvailable(choice.mEventPointer)) { const auto fontStyle = BAK::State::ReadConversationItemClicked(mGameState, choice.mEventPointer) ? '\xf4' // unbold : '#'; choices.emplace_back( std::make_pair( BAK::ChoiceIndex{choice.mEventPointer}, fontStyle + std::string{ mKeywords.GetDialogChoice(choice.mEventPointer)})); } } } choices.emplace_back(std::make_pair(-1, "Goodbye")); constexpr auto buttonSize = glm::vec2{68, 14}; mChoices.StartChoices(choices, buttonSize); mDialogDisplay.Clear(); if (mDialogScene) { mDialogDisplay.ShowWorldViewPane(mInWorldView); mDialogDisplay.DisplayPlayer(*mDialogScene, GetSnippet().mActor); } mScreenStack.PushScreen(&mChoices); } void DialogRunner::ShowQueryChoices() { mLogger.Debug() << "QueryChoices: " << GetSnippet() << "\n"; mLogger.Debug() << "Last text dims:" << mTextDims << "\n"; mChoices.SetPosition(glm::vec2{100, mTextDims.y}); mChoices.SetDimensions(glm::vec2{285, 66}); auto choices = std::vector<std::pair<BAK::ChoiceIndex, std::string>>{}; unsigned i = 0; for (const auto& c : GetSnippet().GetChoices()) { if (std::holds_alternative<BAK::QueryChoice>(c.mChoice)) { const auto index = std::get<BAK::QueryChoice>(c.mChoice).mQueryIndex; mLogger.Debug() << " Choice Index: " << index << "\n"; choices.emplace_back( std::make_pair( BAK::ChoiceIndex{index}, "#" + std::string{ mKeywords.GetQueryChoice(index)})); } else { throw std::runtime_error("Non-query choice in query choice display"); } } if (choices.size() == 0) { assert(false); // I don't think this will be necessary anymore const auto index = BAK::Keywords::sYesIndex; // Yes choices.emplace_back( std::make_pair( BAK::ChoiceIndex{index}, "#" + std::string{mKeywords.GetQueryChoice(index)})); } if (choices.size() == 1) { assert(false); // I don't think this will be necessary anymore const auto availableChoice = choices.back().first; const auto index = availableChoice.mValue == BAK::Keywords::sNoIndex ? BAK::Keywords::sYesIndex : BAK::Keywords::sNoIndex; choices.emplace_back( std::make_pair( BAK::ChoiceIndex{index}, "#" + std::string{mKeywords.GetQueryChoice(index)})); } constexpr auto buttonSize = glm::vec2{32, 14}; mChoices.StartChoices(choices, buttonSize); mScreenStack.PushScreen(&mChoices); } void DialogRunner::ContinueDialogFromStack() { mRemainingText.clear(); mCurrentTarget.reset(); RunDialog(); } bool DialogRunner::RunDialog() { mLogger.Debug() << "RunDialog rem: [" << mRemainingText << "] CurTarg: " << mCurrentTarget <<"\n"; if (!mRemainingText.empty()) { DisplaySnippet(); if (mRemainingText.empty() && GetSnippet().IsQueryChoice()) ShowQueryChoices(); return true; } if (mCurrentTarget && GetSnippet().IsQueryChoice()) { ShowQueryChoices(); return true; } do { const auto nextTarget = GetNextTarget(); mLogger.Debug() << "Curr: " << mCurrentTarget << " Next Target: " << nextTarget << "\n"; if (!nextTarget || (std::holds_alternative<BAK::KeyTarget>(*nextTarget) && std::get<BAK::KeyTarget>(*nextTarget) == BAK::KeyTarget{0x0})) { CompleteDialog(); return false; } else { mCurrentTarget = *nextTarget; EvaluateSnippetActions(); mLogger.Debug() << "Progressing through: " << GetSnippet() << "\n"; } } while (!mCurrentTarget || !GetSnippet().IsDisplayable()); if (GetSnippet().IsDialogChoice()) ShowDialogChoices(); else DisplaySnippet(); if (GetSnippet().IsQueryChoice() && mRemainingText.empty()) ShowQueryChoices(); return true; } void DialogRunner::CompleteDialog() { mLogger.Debug() << "Finished dialog\n"; mDialogDisplay.Clear(); mDialogState.DeactivateDialog(); mDialogScene = nullptr; mCurrentTarget.reset(); mRemainingText.clear(); if (mStartedMusic) { AudioA::AudioManager::Get().PopTrack(); mStartedMusic = false; } std::invoke(mFinished, GetLastChoice()); // reset last choice...? } BAK::Target DialogRunner::GetAndPopTargetStack() { ASSERT(!mTargetStack.empty()); const auto target = mTargetStack.top(); mTargetStack.pop(); return target; } }
13,935
C++
.cpp
444
23.36036
130
0.582458
xavieran/BaKGL
39
2
32
GPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,440
bookPlayer.cpp
xavieran_BaKGL/gui/bookPlayer.cpp
#include "gui/bookPlayer.hpp" #include "bak/fileBufferFactory.hpp" namespace Gui { BookPlayer::BookPlayer( Graphics::SpriteManager& spriteManager, const Font& font, const Backgrounds& background, std::function<void()> finishedBook) : mSpriteManager{spriteManager}, mSpriteSheet{spriteManager.AddTemporarySpriteSheet()}, mFont{font}, mTextures{}, mBackground{ ImageTag{}, background.GetSpriteSheet(), background.GetScreen("BOOK.SCX"), {0, 0}, {320, 200}, true}, mTextBox{{}, {}}, mFinishedBook{std::move(finishedBook)} { auto bookTextures = Graphics::TextureStore{}; BAK::TextureFactory::AddToTextureStore( mTextures, "BOOK.BMX", "BOOK.PAL"); spriteManager.GetSpriteSheet(mSpriteSheet->mSpriteSheet).LoadTexturesGL(mTextures); } void BookPlayer::PlayBook(std::string book) { auto fb = BAK::FileBufferFactory::Get().CreateDataBuffer(book); mBook = BAK::LoadBook(fb); mCurrentPage = 0; std::stringstream ss{}; ss << " "; for (const auto& p : mBook->mPages[mCurrentPage].mParagraphs) { ss << " "; for (const auto& t : p.mText) { if ((static_cast<unsigned>(t.mFontStyle) & static_cast<unsigned>(BAK::FontStyle::Italic)) != 0) { ss << '\xf3'; } ss << t.mText; } ss << "\n\xf8"; } mText = ss.str(); RenderPage(mBook->mPages[mCurrentPage]); } void BookPlayer::AdvancePage() { if (mText.empty()) { mFinishedBook(); return; } mCurrentPage++; if (mCurrentPage == mBook->mPages.size()) { mCurrentPage = 0; } RenderPage(mBook->mPages[mCurrentPage]); } void BookPlayer::RenderPage(const BAK::Page& page) { Logging::LogDebug(__FUNCTION__) << page << "\n"; mBackground.ClearChildren(); mImages.clear(); for (const auto& image : page.mImages) { auto pos = image.mPos / 2; auto dims = mTextures.GetTexture(image.mImage).GetDims() / 2; mImages.emplace_back(Widget{ ImageTag{}, mSpriteSheet->mSpriteSheet, Graphics::TextureIndex{image.mImage}, pos, dims, false}); if (image.mMirroring == BAK::Mirroring::HorizontalAndVertical) { mImages.back().SetPosition(pos + dims); mImages.back().SetDimensions(-dims); } } for (auto& w : mImages) { mBackground.AddChildBack(&w); } mTextBox.SetPosition(mBook->mPages[mCurrentPage].mOffset / 2); mTextBox.SetDimensions(mBook->mPages[mCurrentPage].mDims / 2); auto [pos, remaining] = mTextBox.SetText(mFont, mText, false, false, false, .82, 2.0); mText = remaining; Logging::LogDebug(__FUNCTION__) << "Remaining text: " << mText << "\n"; mBackground.AddChildBack(&mTextBox); } Widget* BookPlayer::GetBackground() { return &mBackground; } }
2,997
C++
.cpp
103
22.883495
107
0.616186
xavieran/BaKGL
39
2
32
GPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,441
staticTTM.cpp
xavieran_BaKGL/gui/staticTTM.cpp
#include "gui/staticTTM.hpp" #include "bak/textureFactory.hpp" #include "com/assert.hpp" #include "com/logger.hpp" #include "graphics/types.hpp" #include "gui/colors.hpp" namespace Gui { StaticTTM::StaticTTM( Graphics::SpriteManager& spriteManager, const BAK::Scene& sceneInit, const BAK::Scene& sceneContent) : mSpriteSheet{spriteManager.AddTemporarySpriteSheet()}, mSceneFrame{ Graphics::DrawMode::Rect, mSpriteSheet->mSpriteSheet, Graphics::TextureIndex{0}, Graphics::ColorMode::SolidColor, glm::vec4{0}, glm::vec2{0}, glm::vec2{1}, false }, mDialogBackground{}, mSceneElements{}, mClipRegion{}, mLogger{Logging::LogState::GetLogger("Gui::StaticTTM")} { mLogger.Debug() << "Loading scene: " << sceneInit << " with " << sceneContent << std::endl; auto textures = Graphics::TextureStore{}; std::unordered_map<unsigned, unsigned> offsets{}; // Load all the image slots for (const auto& scene : {sceneInit, sceneContent}) { for (const auto& [imageKey, imagePal] : scene.mImages) { const auto& [image, palKey] = imagePal; assert(scene.mPalettes.find(palKey) != scene.mPalettes.end()); const auto& palette = scene.mPalettes.find(palKey)->second; mLogger.Debug() << "Loading image slot: " << imageKey << " (" << image << ") with palette: " << palKey << std::endl; offsets[imageKey] = textures.GetTextures().size(); BAK::TextureFactory::AddToTextureStore( textures, image, palette); } for (const auto& [screenKey, screenPal] : scene.mScreens) { const auto& [screen, palKey] = screenPal; const auto& palette = scene.mPalettes.find(palKey)->second; mLogger.Debug() << "Loading screen slot: " << screenKey << " (" << screen << ") with palette: " << palKey << std::endl; offsets[25] = textures.GetTextures().size(); BAK::TextureFactory::AddScreenToTextureStore( textures, screen, palette); } } // Make sure all the refs are constant mSceneElements.reserve( sceneInit.mActions.size() + sceneContent.mActions.size()); // Some scenes will have a dialog background specified in slot 5 // Find and add it if so constexpr auto DIALOG_BACKGROUND_SLOT = 5; const auto dialogBackground = offsets.find(DIALOG_BACKGROUND_SLOT); if (dialogBackground != offsets.end()) { const auto texture = dialogBackground->second; mDialogBackground.emplace( Graphics::DrawMode::Sprite, mSpriteSheet->mSpriteSheet, Graphics::TextureIndex{texture}, Graphics::ColorMode::Texture, glm::vec4{1}, glm::vec2{0}, glm::vec2{1}, false ); } // Add widgets for each scene action for (const auto& scene : {sceneInit, sceneContent}) { for (const auto& action : scene.mActions) { std::visit( overloaded{ [&](const BAK::DrawScreen& sa){ mLogger.Info() << "DrawScreen: " << sa << "\n"; const auto screen = ConvertSceneAction( sa, textures, offsets); auto& elem = mSceneElements.emplace_back( Graphics::DrawMode::Sprite, mSpriteSheet->mSpriteSheet, Graphics::TextureIndex{screen.mImage}, Graphics::ColorMode::Texture, glm::vec4{1}, screen.mPosition, screen.mScale, false); // Either add to the clip region or to the frame // This doesn't work if the scene has more than one // clip region... if (mClipRegion) mClipRegion->AddChildBack(&elem); else mSceneFrame.AddChildBack(&elem); }, [&](const BAK::DrawSprite& sa){ const auto sceneSprite = ConvertSceneAction( sa, textures, offsets); auto& elem = mSceneElements.emplace_back( Graphics::DrawMode::Sprite, mSpriteSheet->mSpriteSheet, Graphics::TextureIndex{sceneSprite.mImage}, Graphics::ColorMode::Texture, glm::vec4{1}, sceneSprite.mPosition, sceneSprite.mScale, false); // Either add to the clip region or to the frame // This doesn't work if the scene has more than one // clip region... if (mClipRegion) mClipRegion->AddChildBack(&elem); else mSceneFrame.AddChildBack(&elem); }, [&](const BAK::DrawRect& sr){ constexpr auto FRAME_COLOR_INDEX = 6; const auto [palKey, colorKey] = sr.mPaletteColor; const auto sceneRect = SceneRect{ // Reddy brown frame color colorKey == FRAME_COLOR_INDEX ? Gui::Color::frameMaroon : Gui::Color::black, glm::vec2{sr.mPos.x, sr.mPos.y}, glm::vec2{sr.mDims.x, sr.mDims.y}}; // This really only works for "DrawFrame", not "DrawRect" mSceneFrame.SetPosition(sceneRect.mPosition); mSceneFrame.SetDimensions(sceneRect.mDimensions); mSceneFrame.SetColor(sceneRect.mColor); // DialogBackground will have same dims... if (mDialogBackground) { mDialogBackground->SetPosition(sceneRect.mPosition + glm::vec2{1,1}); mDialogBackground->SetDimensions(sceneRect.mDimensions - glm::vec2{2, 2}); } }, [&](const BAK::ClipRegion& a){ const auto clip = ConvertSceneAction(a); mClipRegion.emplace( ClipRegionTag{}, clip.mTopLeft, clip.mDims, false); mSceneFrame.AddChildBack(&(*mClipRegion)); }, [&](const BAK::DisableClipRegion&){ // Doesn't really do anything... // in the future maybe pop the clip region // so we could add another one? }, [&](const auto&){} }, action ); } } spriteManager .GetSpriteSheet(mSpriteSheet->mSpriteSheet) .LoadTexturesGL(textures); } Widget* StaticTTM::GetScene() { return &mSceneFrame; } Widget* StaticTTM::GetBackground() { ASSERT(mDialogBackground); return &(*mDialogBackground); } }
7,872
C++
.cpp
189
25.619048
102
0.48486
xavieran/BaKGL
39
2
32
GPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false