Files
shadow-over-bishkek001/server/tests/LocationGameStateTests.cpp
T
2026-11-17 20:29:20 +06:00

439 lines
17 KiB
C++

#include "LocationGameState.h"
#include "game_server/InternalGameServer.h"
#include <algorithm>
#include <cmath>
#include <cstdlib>
#include <filesystem>
#include <fstream>
#include <iostream>
namespace {
int fail(const char* message)
{
std::cout << "LocationGameStateTests: " << message << std::endl;
return EXIT_FAILURE;
}
FRG::Vec3fp point(float x, float y, float z)
{
return {
static_cast<FRG::fp>(x),
static_cast<FRG::fp>(y),
static_cast<FRG::fp>(z)};
}
bool samePoint(const FRG::Vec3fp& left, const FRG::Vec3fp& right)
{
return left.x == right.x && left.y == right.y && left.z == right.z;
}
} // namespace
int main()
{
FRG::ClientLocationState localState;
auto camera = localState.getOrCreate("test_location");
camera->cameraAzimuth = 0.75f;
camera->cameraInclination = 1.25f;
nlohmann::json localJson;
localState.save(localJson);
FRG::ClientLocationState restoredLocalState;
restoredLocalState.load(localJson);
const auto restoredCamera =
restoredLocalState.getOrCreate("test_location");
if (restoredCamera->cameraAzimuth != 0.75f ||
restoredCamera->cameraInclination != 1.25f) {
return fail("Local camera state did not round trip");
}
FRG::LocationNetworkState networkLocationState;
nlohmann::json networkLocationJson;
networkLocationState.save(networkLocationJson);
if (networkLocationJson.contains("cameraAzimuth") ||
networkLocationJson.contains("cameraInclination")) {
return fail("Network location state contains local camera fields");
}
const nlohmann::json authoritativeJson{
{"schemaVersion", FRG::GameState::kSchemaVersion},
{"campaignId", "test"}
};
nlohmann::json persistenceJson;
FRG::saveSinglePlayerPersistence(
authoritativeJson, localState, persistenceJson);
nlohmann::json restoredAuthoritativeJson;
FRG::ClientLocationState restoredPersistenceLocalState;
FRG::loadSinglePlayerPersistence(
persistenceJson, restoredAuthoritativeJson,
restoredPersistenceLocalState);
if (restoredAuthoritativeJson != authoritativeJson ||
restoredPersistenceLocalState.getOrCreate("test_location")
->cameraAzimuth != 0.75f) {
return fail("Composed single-player state did not round trip");
}
if (persistenceJson.at("networkState").contains("localState")) {
return fail("Local state leaked into authoritative state");
}
const std::filesystem::path repositoryRoot =
std::filesystem::path(__FILE__).parent_path().parent_path().parent_path();
std::filesystem::current_path(repositoryRoot);
FRG::CampaignRegistry::instance().loadFromJson(
"resources/config/campaigns.json");
const FRG::CampaignConfig* singlePlayerBattleZone =
FRG::CampaignRegistry::instance().find("battle_zone");
const FRG::CampaignConfig* multiplayerBattleZoneConfig =
FRG::CampaignRegistry::instance().find("battle_zone_multiplayer");
if (FRG::CampaignRegistry::instance().all().size() != 3 ||
!singlePlayerBattleZone || !multiplayerBattleZoneConfig) {
return fail("Expected three campaigns including both Battle Zone modes");
}
if (singlePlayerBattleZone->startStatePath.empty() ||
multiplayerBattleZoneConfig->startStatePath.empty()) {
return fail("Battle Zone modes are missing initial state paths");
}
if (multiplayerBattleZoneConfig->networkPlayerSlots.size() != 4 ||
multiplayerBattleZoneConfig->networkPlayerSlots[0] != "player1" ||
multiplayerBattleZoneConfig->networkPlayerSlots[1] !=
"player2" ||
multiplayerBattleZoneConfig->networkPlayerSlots[2] != "player3" ||
multiplayerBattleZoneConfig->networkPlayerSlots[3] != "player4" ||
multiplayerBattleZoneConfig->networkCompatibility.empty()) {
return fail("Multiplayer player slots were not loaded");
}
const std::string compatibilityFingerprint =
FRG::makeNetworkCompatibilityFingerprint(
*multiplayerBattleZoneConfig);
FRG::CampaignConfig reorderedContent = *multiplayerBattleZoneConfig;
if (reorderedContent.locations.empty() ||
reorderedContent.locations.front().navigationJsonPaths.size() < 2) {
return fail("Expected multiple navigation maps for fingerprint test");
}
std::reverse(
reorderedContent.locations.front().navigationJsonPaths.begin(),
reorderedContent.locations.front().navigationJsonPaths.end());
if (compatibilityFingerprint ==
FRG::makeNetworkCompatibilityFingerprint(reorderedContent)) {
return fail("Compatibility fingerprint ignored navigation-map order");
}
const std::filesystem::path lineEndingResource =
std::filesystem::temp_directory_path() /
"frg_fingerprint_line_endings.json";
FRG::CampaignConfig lineEndingCampaign;
lineEndingCampaign.id = "line_endings";
lineEndingCampaign.networkCompatibility = "line-endings-test";
lineEndingCampaign.locationConfigPaths = {
lineEndingResource.string()};
FRG::LocationConfig lineEndingLocation;
lineEndingLocation.id = "test";
lineEndingCampaign.locations.push_back(lineEndingLocation);
{
std::ofstream output(lineEndingResource, std::ios::binary);
output << "{\r\n \"id\": \"test\"\r\n}\r\n";
}
const std::string crlfFingerprint =
FRG::makeNetworkCompatibilityFingerprint(lineEndingCampaign);
{
std::ofstream output(
lineEndingResource, std::ios::binary | std::ios::trunc);
output << "{\n \"id\": \"test\"\n}\n";
}
const std::string lfFingerprint =
FRG::makeNetworkCompatibilityFingerprint(lineEndingCampaign);
std::filesystem::remove(lineEndingResource);
if (crlfFingerprint != lfFingerprint) {
return fail("Compatibility fingerprint depends on line endings");
}
FRG::LocationDefinition definition;
definition.config.id = "test_location";
FRG::NpcData npc;
npc.id = "npc";
npc.name = "Test NPC";
npc.hp = 75.f;
definition.npcs.push_back(npc);
FRG::InteractiveObjectData object;
object.id = "object";
object.base.name = "Test Object";
object.base.meshPath = "unused.mesh";
object.isActive = true;
definition.interactiveObjects.push_back(object);
FRG::TriggerZoneDefinition trigger;
trigger.id = "trigger";
trigger.enabled = true;
definition.triggerZones.push_back(trigger);
FRG::TeleportDefinition teleport;
teleport.id = "teleport";
teleport.active = false;
definition.teleports.push_back(teleport);
FRG::LocationGameState state;
if (!state.setup(definition, {}))
return fail("First setup must initialize runtime fields");
if (state.npcs.size() != 1 || state.interactiveObjects.size() != 1)
return fail("Definitions were not applied");
state.npcs.at("npc")->hp = 12.f;
state.interactiveObjects.at("object")->isActive = false;
state.triggerZones.at("trigger").enabled = false;
state.teleportZones.at("teleport") = true;
state.hasPersistentState = true;
if (state.setup(definition, {}))
return fail("Persistent setup must not reinitialize runtime fields");
if (state.npcs.at("npc")->hp != 12.f ||
state.interactiveObjects.at("object")->isActive ||
state.triggerZones.at("trigger").enabled ||
!state.teleportZones.at("teleport")) {
return fail("Repeated setup did not preserve runtime state");
}
FRG::PlayerStateMap noPlayers;
state.update(50, noPlayers, false);
auto disabledPlayer = std::make_shared<FRG::CharacterState>();
disabledPlayer->configureAsPlayer();
disabledPlayer->enabled = false;
state.location->targetInteractiveObjectId = "object";
state.location->targetInteractNpcId = "npc";
FRG::PlayerStateMap disabledPlayers{{"player1", disabledPlayer}};
const FRG::LocationSimulationEvents disabledEvents =
state.update(50, disabledPlayers, false);
if (!disabledEvents.interactiveObjects.empty() ||
!disabledEvents.npcInteractionId.empty()) {
return fail("Disabled player interacted with location entities");
}
auto& hostileNpc = *state.npcs.at("npc");
hostileNpc.enabled = true;
hostileNpc.canAttack = true;
hostileNpc.hp = hostileNpc.initialHp = 75.f;
hostileNpc.position = point(0.f, 0.f, 0.f);
hostileNpc.homePosition = point(5.f, 0.f, 0.f);
hostileNpc.stopInPlace();
auto playerOne = std::make_shared<FRG::CharacterState>();
playerOne->configureAsPlayer();
playerOne->enabled = true;
playerOne->position = point(3.f, 0.f, 0.f);
auto playerTwo = std::make_shared<FRG::CharacterState>();
playerTwo->configureAsPlayer();
playerTwo->enabled = true;
playerTwo->position = point(2.f, 0.f, 0.f);
FRG::PlayerStateMap combatPlayers{
{"player1", playerOne}, {"player2", playerTwo}};
state.update(100, combatPlayers, false);
if (hostileNpc.attackTargetId != "player2") {
return fail("Hostile NPC did not select the nearest player");
}
playerOne->position = point(1.f, 0.f, 0.f);
playerTwo->position = point(4.f, 0.f, 0.f);
state.update(100, combatPlayers, false);
if (hostileNpc.attackTargetId != "player2") {
return fail("Hostile NPC did not retain its living target lock");
}
playerTwo->hp = 0.f;
state.update(100, combatPlayers, false);
if (hostileNpc.attackTargetId != "player1") {
return fail("Hostile NPC did not acquire a replacement after target death");
}
playerOne->enabled = false;
state.update(100, combatPlayers, false);
if (!hostileNpc.attackTargetId.empty() ||
hostileNpc.battle_state != 0 ||
(hostileNpc.requestedWalkTarget -
hostileNpc.homePosition).normSquared() >
FRG::CharacterState::kWalkThreshold_SQUARED()) {
return fail("Hostile NPC did not return home after losing its target");
}
FRG::CampaignConfig battleZone;
battleZone.id = "battle_zone";
battleZone.questsPath = "resources/config/quests_battle_zone.json";
FRG::InternalGameServer server;
server.startCampaign(battleZone, {}, false, true);
const auto snapshot = server.snapshot();
const auto bot = snapshot->players.find("player2");
if (bot == snapshot->players.end())
return fail("Battle Zone test bot was not created");
const auto stand = static_cast<std::size_t>(FRG::AnimationState::STAND);
const auto walk = static_cast<std::size_t>(FRG::AnimationState::WALK);
if (bot->second.state.animationFrameCounts[stand] <= 1 ||
bot->second.state.animationFrameCounts[walk] <= 1) {
return fail("Battle Zone test bot animation metadata was not loaded");
}
FRG::InternalGameServer networkServer;
FRG::CampaignConfig multiplayerBattleZone = battleZone;
multiplayerBattleZone.id = "battle_zone_multiplayer";
multiplayerBattleZone.networkPlayerSlots = {
"player1", "player2"};
networkServer.startCampaign(multiplayerBattleZone, {}, true, false);
const auto networkSnapshot = networkServer.snapshot();
if (networkSnapshot->campaignId != "battle_zone_multiplayer")
return fail("Network campaign ID was not retained");
if (networkSnapshot->players.count("player1") != 1)
return fail("Network campaign shared player was not created");
if (networkSnapshot->players.count("player2") != 0)
return fail("Network campaign unexpectedly created the test bot");
if (networkSnapshot->players.at("player1").state.enabled)
return fail("Network campaign player slot was enabled before connection");
nlohmann::json loadedNetworkState;
networkServer.save(loadedNetworkState);
loadedNetworkState["players"]["player2"] =
loadedNetworkState["players"]["player1"];
loadedNetworkState["players"]["player2"]["position"] =
{4.f, 0.f, 5.f};
networkServer.load(loadedNetworkState);
const auto loadedNetworkSnapshot = networkServer.snapshot();
const auto loadedNetworkBot =
loadedNetworkSnapshot->players.find("player2");
if (loadedNetworkBot == loadedNetworkSnapshot->players.end() ||
loadedNetworkBot->second.state.animationFrameCounts[stand] <= 1 ||
loadedNetworkBot->second.state.animationFrameCounts[walk] <= 1) {
return fail(
"Loaded multiplayer slot did not restore animation metadata");
}
if (!samePoint(
loadedNetworkBot->second.state.position,
point(4.f, 0.f, 5.f))) {
return fail("Loaded multiplayer slot position was overwritten");
}
if (loadedNetworkBot->second.state.enabled)
return fail("Loaded multiplayer slot was enabled before connection");
const std::string locationId = loadedNetworkSnapshot->currentLocationId;
networkServer.submit(FRG::SetCharacterPositionCommand{
locationId, "player2", point(7.f, 0.f, 8.f), true});
networkServer.submit(FRG::SetCharacterFacingAngleCommand{
locationId, "player2", FRG::fp(1.5f), true});
networkServer.submit(FRG::SetCharacterFaceTargetCommand{
locationId, "player2", "player1"});
networkServer.submit(FRG::SetCharacterEnabledCommand{
locationId, "player2", false});
const auto commandSnapshot = networkServer.snapshot();
const auto commandCharacter = commandSnapshot->players.at("player2").state;
if (!samePoint(commandCharacter.position, point(7.f, 0.f, 8.f)) ||
!samePoint(commandCharacter.homePosition, point(7.f, 0.f, 8.f)) ||
commandCharacter.facingAngle != FRG::fp(1.5f) ||
commandCharacter.targetFacingAngle != FRG::fp(1.5f) ||
!commandCharacter.faceTargetId.empty() ||
commandCharacter.enabled) {
return fail("Semantic character commands were not applied");
}
networkServer.submit(FRG::SetCharacterEnabledCommand{
locationId, "player2", true});
const auto enabledPlayer =
networkServer.snapshot()->players.at("player2").state;
if (!enabledPlayer.enabled || !enabledPlayer.attackTargetId.empty()) {
return fail("Enabled player acquired an autonomous attack target");
}
FRG::CharacterState drawAnimation;
drawAnimation.configureAsPlayer();
drawAnimation.enabled = true;
drawAnimation.setAnimationMetadata(
FRG::AnimationState::STAND_TO_ACTION, 0, 100);
drawAnimation.setAnimationMetadata(
FRG::AnimationState::ACTION_IDLE, 0, 100);
FRG::CharacterObservation attackTarget{
point(0.f, 0.f, 1.f), 100.f};
drawAnimation.update(100, {&attackTarget, nullptr});
if (drawAnimation.currentState != FRG::AnimationState::STAND_TO_ACTION ||
std::abs(drawAnimation.animationFrame - 8.333333f) > 0.001f ||
drawAnimation.showWeapon) {
return fail("Weapon draw animation did not advance at 2x speed");
}
drawAnimation.update(200, {&attackTarget, nullptr});
if (!drawAnimation.showWeapon) {
return fail("Weapon draw animation did not use its frame visibility threshold");
}
FRG::CharacterState sheathAnimation;
sheathAnimation.configureAsPlayer();
sheathAnimation.enabled = true;
sheathAnimation.currentState = FRG::AnimationState::ACTION_IDLE;
sheathAnimation.setAnimationMetadata(
FRG::AnimationState::ACTION_TO_STAND, 0, 100);
sheathAnimation.update(100, {nullptr, nullptr});
if (sheathAnimation.currentState != FRG::AnimationState::ACTION_TO_STAND ||
std::abs(sheathAnimation.animationFrame - 8.333333f) > 0.001f ||
!sheathAnimation.showWeapon) {
return fail("Weapon sheath animation did not advance at 2x speed");
}
sheathAnimation.update(300, {nullptr, nullptr});
if (sheathAnimation.showWeapon) {
return fail("Weapon sheath animation did not hide at its frame visibility threshold");
}
FRG::CharacterState ordinaryAnimation;
ordinaryAnimation.configureAsPlayer();
ordinaryAnimation.enabled = true;
ordinaryAnimation.currentState = FRG::AnimationState::STAND;
ordinaryAnimation.setAnimationMetadata(
FRG::AnimationState::STAND, 0, 100);
ordinaryAnimation.update(100, {nullptr, nullptr});
if (std::abs(ordinaryAnimation.animationFrame - 4.1666665f) > 0.001f) {
return fail("Ordinary animation playback rate changed unexpectedly");
}
FRG::CharacterState completedDrawAnimation;
completedDrawAnimation.configureAsPlayer();
completedDrawAnimation.enabled = true;
completedDrawAnimation.setAnimationMetadata(
FRG::AnimationState::STAND_TO_ACTION, 0, 30);
completedDrawAnimation.setAnimationMetadata(
FRG::AnimationState::ACTION_IDLE, 0, 30);
for (int i = 0; i < 4; ++i)
completedDrawAnimation.update(
100, {&attackTarget, nullptr});
if (completedDrawAnimation.currentState !=
FRG::AnimationState::ACTION_IDLE) {
return fail("Accelerated weapon draw animation did not complete");
}
FRG::CharacterState completedSheathAnimation;
completedSheathAnimation.configureAsPlayer();
completedSheathAnimation.enabled = true;
completedSheathAnimation.currentState = FRG::AnimationState::ACTION_IDLE;
completedSheathAnimation.setAnimationMetadata(
FRG::AnimationState::ACTION_TO_STAND, 0, 30);
for (int i = 0; i < 4; ++i)
completedSheathAnimation.update(
100, {nullptr, nullptr});
if (completedSheathAnimation.currentState != FRG::AnimationState::STAND) {
return fail("Accelerated weapon sheath animation did not complete");
}
FRG::CharacterState guardedMover;
nlohmann::json guardedJson;
guardedMover.velocity = {
FRG::fp::from_raw_value(12345),
FRG::fp::from_raw_value(-6789)};
guardedMover.navigationOutcome =
FRG::PathFinder::PathOutcome::NearestReachable;
guardedMover.save(guardedJson);
FRG::CharacterState restoredGuardedMover;
restoredGuardedMover.load(guardedJson);
if (restoredGuardedMover.navigationRetryTicks !=
guardedMover.navigationRetryTicks ||
restoredGuardedMover.velocity.x.raw_value() != 12345 ||
restoredGuardedMover.velocity.y.raw_value() != -6789 ||
restoredGuardedMover.navigationOutcome !=
FRG::PathFinder::PathOutcome::NearestReachable) {
return fail("Character velocity did not round trip");
}
return EXIT_SUCCESS;
}