Files
DarkflameServer/dScripts/ai/MINIGAME/ShootingGallery/ShootingGalleryCannon.cpp
Aaron Kimbrell 8d059ab1c8 feat(scripts): shooting gallery cannon and zone re-ported from the original
SG_CANNON.lua and L_GF_SG.lua line for line, as a shared cannon and
zone script (ShootingGallery folder) that a gallery fills with its
constants and targets; GF's (SGCannon, ZoneSGServer) is now that data.
The cannon gets the zone control's ActivityStateChangeRequest,
MessageBoxRespond and ObjectLoaded from the zone script, as the
original asked to be told of them.

As the original: waves end through their own EndWave<n> timer and the
last one through GameOver; targets spawn 1 s or more after their timer
starts; scores are counted at the shot's end and can go below 0; the
super charge is the shot of its cannon ball; one activity reward roll,
rated by the score; the wave, fire and preload animations and effects;
GF's spawn table as the original's.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 21:54:26 -06:00

1139 lines
43 KiB
C++

#include "ShootingGalleryCannon.h"
#include "ShootingGalleryLogic.h"
#include "SgTarget.h"
#include "ActivityMessages.h"
#include "BuildingMessages.h"
#include "Character.h"
#include "CharacterComponent.h"
#include "DestroyableComponent.h"
#include "EffectsMessages.h"
#include "Entity.h"
#include "EntityManager.h"
#include "GameMessages.h"
#include "GeneralUtils.h"
#include "InventoryComponent.h"
#include "Item.h"
#include "Loot.h"
#include "MissionComponent.h"
#include "MovementAIComponent.h"
#include "MovingPlatformComponent.h"
#include "PlayerManager.h"
#include "PossessorComponent.h"
#include "RenderComponent.h"
#include "ShootingGalleryComponent.h"
#include "SimplePhysicsComponent.h"
#include "SkillComponent.h"
#include "Zone.h"
#include "dZoneManager.h"
#include "eGameActivity.h"
#include "eKillType.h"
#include "eMissionTaskType.h"
#include <ranges>
namespace {
// for Animations
const std::vector<LOT> VALID_ACTORS = { 3109, 3110, 3111, 3112, 3125, 3126 };
const std::vector<LOT> VALID_EFFECTS = { 3122 };
const std::vector<int32_t> STREAK_BONUS = { 1, 2, 5, 10 };
const std::string SuperChargeTimer = "Super_Charge_Timer";
const std::string SpawnWaveTimer = "SpawnWave";
const std::string EndWaveTimer = "EndWave";
const std::string GameOverTimer = "GameOver";
const std::string DoSpawnTimer = "DoSpawn";
const std::string EndGameBufferTimer = "endGameBuffer";
// math.random()
float Random01() {
return GeneralUtils::GenerateRandomNumber<float>(0.0f, 1.0f);
}
// math.random(m, n)
int32_t RandomRange(const int32_t m, const int32_t n) {
return GeneralUtils::GenerateRandomNumber<int32_t>(m, n);
}
};
ShootingGalleryCannon::State& ShootingGalleryCannon::GetState(const Entity* self) {
return m_States[self->GetObjectID()];
}
Entity* ShootingGalleryCannon::GetActivityUser(const Entity* self) const {
const auto* const shootingGallery = self->GetComponent<ShootingGalleryComponent>();
if (shootingGallery == nullptr) return nullptr;
return Game::entityManager->GetEntity(shootingGallery->GetCurrentPlayerID());
}
Entity* ShootingGalleryCannon::GetActivityPlayer(Entity* self) {
return Game::entityManager->GetEntity(GetState(self).activityPlayer);
}
// SetShootingGalleryParams: the cannon's shooting gallery component takes them and sends them to the clients
void ShootingGalleryCannon::SetShootingGalleryParams(Entity* self, const float cooldown, const float timeLimit) {
auto* const shootingGallery = self->GetComponent<ShootingGalleryComponent>();
if (shootingGallery == nullptr) return;
const auto& g_const = GetConstants();
auto params = shootingGallery->GetDynamicParams();
if (g_const.CANNON_BARREL_OFFSET) params.cameraBarrelOffset = *g_const.CANNON_BARREL_OFFSET;
params.cannonVelocity = g_const.CANNON_VELOCITY;
params.cannonRefireRate = cooldown;
params.cannonMinDistance = g_const.CANNON_MIN_DISTANCE;
params.cannonTimeout = timeLimit;
params.cannonFOV = g_const.CANNON_FOV;
shootingGallery->SetDynamicParams(params);
Game::entityManager->SerializeEntity(self);
}
// RequestActivitySummaryLeaderboardData{target = self, queryType = 1, gameID = activityID} on the activity user
void ShootingGalleryCannon::RequestActivitySummaryLeaderboardData(Entity* self) {
const auto* const user = GetActivityUser(self);
if (user == nullptr) return;
GetLeaderboardData(self, user->GetObjectID(), GetConstants().ActivityID, 10);
}
// ActivityPause{rerouteID = player, bPause}
void ShootingGalleryCannon::ActivityPause(Entity* self, Entity* player, const bool bPause) {
if (player == nullptr) return;
GameMessages::ActivityPause activityPause;
activityPause.target = self->GetObjectID();
activityPause.bPause = bPause;
activityPause.Send(player->GetSystemAddress());
}
// ActivityStop{rerouteID = player, bExit, bUserCanceled}: a game played to its end gets the activity's rewards, rated
// by onDoCalculateActivityRating, and its missions
void ShootingGalleryCannon::ActivityStop(Entity* self, Entity* player, const bool bExit, const bool bUserCanceled) {
if (!bUserCanceled) {
const auto& state = GetState(self);
if (auto* const missionComponent = player->GetComponent<MissionComponent>()) {
missionComponent->Progress(eMissionTaskType::PERFORM_ACTIVITY, state.Mym_totalScore, self->GetObjectID(), "performact_score");
missionComponent->Progress(eMissionTaskType::PERFORM_ACTIVITY, state.m_maxStreak, self->GetObjectID(), "performact_streak");
missionComponent->Progress(eMissionTaskType::ACTIVITY, GetConstants().CANNON_TEMPLATEID, 0, "", state.Mym_totalScore);
}
Loot::GiveActivityLoot(player, self->GetObjectID(), GetGameID(self), static_cast<int32_t>(CalculateActivityRating(self, player->GetObjectID())));
}
GameMessages::ActivityStop activityStop;
activityStop.target = self->GetObjectID();
activityStop.bExit = bExit;
activityStop.bUserCancel = bUserCanceled;
activityStop.Send(player->GetSystemAddress());
}
// --------------------------------------------------------------
// onStartup
// --------------------------------------------------------------
void ShootingGalleryCannon::OnStartup(Entity* self) {
auto& state = GetState(self);
// set game state
state.spawns = TargetSettings();
ResetVars(self);
state.GameStarted = false;
state.m_totalScore = 0;
// send an object loaded message to the ZoneControl object
auto* const zoneControl = Game::entityManager->GetZoneControlEntity();
if (zoneControl != nullptr) {
GameMessages::ObjectLoaded objectLoaded;
objectLoaded.objectID = self->GetObjectID();
objectLoaded.lot = self->GetLOT();
objectLoaded.Send(zoneControl->GetObjectID());
}
// StartLuaNotify: the zone script passes its ActivityStateChangeRequest, MessageBoxRespond and ObjectLoaded on
// (ShootingGalleryZone)
// Constants
const auto& g_const = GetConstants();
state.FIRST_WAVE_START_TIME = g_const.FIRST_WAVE_START_TIME;
state.ImpactSkillID = g_const.IMPACT_SKILLID;
auto* const shootingGallery = self->GetComponent<ShootingGalleryComponent>();
if (shootingGallery != nullptr) {
// The camera, which the script does not set
shootingGallery->SetStaticParams({
NiPoint3(-327.8609924316406f, 256.8999938964844f, 1.6482199430465698f),
NiPoint3(-181.4320068359375f, 212.39999389648438f, 2.5182199478149414f)
});
}
SetShootingGalleryParams(self, g_const.CANNON_REFIRE_RATE, g_const.CANNON_TIMEOUT);
state.TIME_LIMIT = g_const.waveTimeLimits.empty() ? 0.0f : g_const.waveTimeLimits.front();
state.Super_Charge_Active = false;
state.Matrix = 1;
state.bInit = true;
if (auto* const simplePhysics = self->GetComponent<SimplePhysicsComponent>()) simplePhysics->SetPhysicsMotionState(5);
Game::entityManager->SerializeEntity(self);
}
// resetVars
void ShootingGalleryCannon::ResetVars(Entity* self) {
auto& state = GetState(self);
state.SpawnNum = 0;
state.CurSpawnNum = 0;
state.ThisWave = 0;
state.GameStarted = false;
state.m_shotsFired = 0;
state.m_maxStreak = 0;
state.m_misses = 0;
state.m_curStreak = 0;
state.Current_Super_Charged_Time = 0.0f;
state.StreakBonus = 0;
state.LastSuperTotal.reset();
state.currentReward = LOT_NULL;
state.rewards = { LOT_NULL };
state.Mym_totalScore = 0;
if (state.bInit) ToggleSuperCharge(self, false);
state.ImpactSkillID = GetConstants().IMPACT_SKILLID;
// reset scores
state.PLAYER_SCORE.assign(GetConstants().NUM_WAVES(), 0);
ActivityTimerStopAllTimers(self);
}
// The first onChildLoaded (firing the loaded projectile) is replaced by the second one, the target spawning; the
// projectile's skill and velocity come from the cannon's skill.
// --------------------------------------------------------------
// PlaySceneAnimation: play animations on all actors in the scene, and others
// --------------------------------------------------------------
void ShootingGalleryCannon::PlaySceneAnimation(Entity* self, const std::string& anim, const bool bPlayCannon, const bool bPlayPlayer, const bool bMustPlay) {
const float priority = bMustPlay ? 1.07f : 0.5f;
for (auto* const friendObject : Game::entityManager->GetEntitiesInGroup("cannongroup")) {
RenderComponent::PlayAnimation(friendObject, anim, priority);
}
// play on cannon
if (bPlayCannon) RenderComponent::PlayAnimation(self, anim, priority);
// play on player
if (bPlayPlayer) {
auto* const player = GetActivityPlayer(self);
if (player != nullptr) RenderComponent::PlayAnimation(player, anim, priority);
}
}
// PlaySceneEffect: play effects on all effects in the scene
void ShootingGalleryCannon::PlaySceneEffect(Entity* self, const std::u16string& effectName) {
for (const auto effectID : GetState(self).EFFECTS) {
GameMessages::PlayFXEffect(effectID, -1, effectName, "").Send(UNASSIGNED_SYSTEM_ADDRESS);
}
}
// --------------------------------------------------------------
// onShootingGalleryFire: called when the client wants to fire
// --------------------------------------------------------------
void ShootingGalleryCannon::OnShootingGalleryFire(Entity& self, GameMessages::ShootingGalleryFire& fire) {
auto& state = GetState(&self);
// CalculateFiringParameters{targetPos, bUseHighArc = false}: the server has no solver for it, so the firing
// velocity counts as found (all three of its axes not 0)
state.m_shotsFired++;
if (auto* const player = GetActivityUser(&self)) {
// PlayFXEffect with ignoreID = player: every client but the player's
GameMessages::PlayFXEffect(self.GetObjectID(), -1, u"onfire", "").BroadcastExcept(player->GetSystemAddress());
GameMessages::PlayFXEffect(self.GetObjectID(), -1, u"onfire2", "").BroadcastExcept(player->GetSystemAddress());
GameMessages::PlayFXEffect(player->GetObjectID(), -1, u"SG-fire", "").BroadcastExcept(player->GetSystemAddress());
}
// Tell the zone control we just fired (its script has no handler)
// play fire animation on actors
PlaySceneAnimation(&self, "fire", false, false);
PlaySceneEffect(&self, u"fire");
}
// onGetFaction (the cannon's faction is the user's) is not ported: the cannon's own faction is what its skill hits with
// toggleSuperCharge
void ShootingGalleryCannon::ToggleSuperCharge(Entity* self, const bool enable) {
auto& state = GetState(self);
const auto& g_const = GetConstants();
uint32_t iSkillID = g_const.CANNON_SKILL;
float iCooldown = g_const.CANNON_REFIRE_RATE;
bool bSetChargedState = false;
// GetInventoryItemInSlot{slot = 0 / 1}
Item* meItem1 = nullptr;
Item* meItem2 = nullptr;
auto* const inventory = self->GetComponent<InventoryComponent>();
if (inventory != nullptr) {
for (auto* const item : inventory->GetInventory(eInventoryType::ITEMS)->GetItems() | std::views::values) {
if (item->GetSlot() == 0) meItem1 = item;
else if (item->GetSlot() == 1) meItem2 = item;
}
}
if (enable && state.Super_Charge_Active) {
return;
} else if (enable && !state.Super_Charge_Active) {
if (inventory != nullptr && meItem1 != nullptr) inventory->EquipItem(meItem1);
if (inventory != nullptr && meItem2 != nullptr) inventory->EquipItem(meItem2);
iSkillID = g_const.CANNON_SUPERCHARGE_SKILL;
iCooldown = 400.0f;
bSetChargedState = true;
} else {
if (inventory != nullptr && meItem1 != nullptr) inventory->UnEquipItem(meItem1);
if (inventory != nullptr && meItem2 != nullptr) inventory->UnEquipItem(meItem2);
state.NumberOfCharges = 0;
}
SetShootingGalleryParams(self, iCooldown, -1.0f);
self->SetNetworkVar<uint64_t>(u"cbskill", iSkillID);
state.Super_Charge_Active = bSetChargedState;
}
// TimerToggle
void ShootingGalleryCannon::TimerToggle(Entity* self, const bool bStart) {
auto& state = GetState(self);
if (bStart) {
self->SetNetworkVar<uint32_t>(u"count", static_cast<uint32_t>(state.TIME_LIMIT));
state.Started = true;
} else {
// Stop Timer on Client
self->SetNetworkVar<bool>(u"Stop", true);
}
}
// pauseChargeCannon
void ShootingGalleryCannon::PauseChargeCannon(Entity* self) {
auto& state = GetState(self);
float superChargeTime = std::ceil(ActivityTimerGetRemainingTime(self, SuperChargeTimer));
if (superChargeTime < 1 && superChargeTime > 0) superChargeTime = 1;
state.Super_Charge_Paused = true;
state.Current_Super_Charged_Time = superChargeTime;
self->SetNetworkVar<float>(u"charge_counting", std::ceil(superChargeTime));
ActivityTimerStop(self, SuperChargeTimer);
}
// StartChargedCannon: a time of 0 is a time (Lua's 0 is true), only none uses ChargedTime
void ShootingGalleryCannon::StartChargedCannon(Entity* self, const std::optional<float> optionalTime) {
auto& state = GetState(self);
const float iTime = optionalTime.value_or(GetConstants().ChargedTime);
state.Super_Charge_Paused = false;
ToggleSuperCharge(self, true);
ActivityTimerStart(self, SuperChargeTimer, 1, iTime);
if (!state.WaveStatus) PauseChargeCannon(self);
}
// updateStreak
void ShootingGalleryCannon::UpdateStreak(Entity* self) {
auto& state = GetState(self);
const auto streakBonus = ShootingGallery::Logic::GetCurrentBonus(state.m_curStreak);
const auto curStreak = state.m_curStreak;
self->SetNetworkVar<int32_t>(u"cStreak", curStreak);
// Update the marks
switch (ShootingGallery::Logic::GetStreakMark(curStreak)) {
case ShootingGallery::Logic::StreakMark::MARK1:
self->SetNetworkVar<bool>(u"Mark1", true);
break;
case ShootingGallery::Logic::StreakMark::MARK2:
self->SetNetworkVar<bool>(u"Mark2", true);
break;
case ShootingGallery::Logic::StreakMark::MARK3:
state.StreakBonus = streakBonus;
self->SetNetworkVar<int32_t>(u"ShowStreak", streakBonus + 1);
self->SetNetworkVar<bool>(u"Mark3", true);
break;
case ShootingGallery::Logic::StreakMark::UNMARK_ALL:
state.StreakBonus = streakBonus;
self->SetNetworkVar<bool>(u"UnMarkAll", true);
break;
case ShootingGallery::Logic::StreakMark::NONE:
break;
}
}
// --------------------------------------------------------------
// onActivityTimerUpdate
// --------------------------------------------------------------
void ShootingGalleryCannon::OnActivityTimerUpdate(Entity* self, const std::string& name, const float_t timeRemaining, const float_t elapsedTime) {
if (name == SuperChargeTimer && !GetState(self).Super_Charge_Paused) {
self->SetNetworkVar<float>(u"charge_counting", timeRemaining);
}
}
// --------------------------------------------------------------
// onActivityTimerDone
// --------------------------------------------------------------
void ShootingGalleryCannon::OnActivityTimerDone(Entity* self, const std::string& name) {
auto& state = GetState(self);
const auto& g_const = GetConstants();
if (name == SuperChargeTimer && !state.Super_Charge_Paused) {
if (state.WaveStatus || state.Current_Super_Charged_Time < 1) {
self->SetNetworkVar<float>(u"charge_counting", 999.0f);
self->SetNetworkVar<float>(u"SuperChargeBar", 0.0f);
ToggleSuperCharge(self, false);
}
} else if (name.starts_with(SpawnWaveTimer)) {
if (state.GameStarted) {
const auto waveNum = state.ThisWave;
auto* const player = GetActivityPlayer(self);
// store this wave number
state.WaveStatus = true;
state.ThisWaveVar = waveNum;
if (waveNum != 1 && state.Super_Charge_Paused) {
StartChargedCannon(self, state.Current_Super_Charged_Time);
state.Current_Super_Charged_Time = 0.0f;
}
TimerToggle(self, true);
// setup spawns for wave
if (waveNum >= 1 && waveNum <= state.spawns.size()) {
auto& waveSpawns = state.spawns[waveNum - 1];
for (uint32_t k = 0; k < waveSpawns.size(); k++) SpawnObject(k, waveSpawns[k], self, true);
}
// there are no more waves left so stop game after this wave
if (waveNum >= g_const.NUM_WAVES()) {
ActivityTimerStart(self, GameOverTimer, state.TIME_LIMIT, state.TIME_LIMIT);
} else {
// setup next wave
ActivityTimerStart(self, EndWaveTimer + std::to_string(waveNum), state.TIME_LIMIT, state.TIME_LIMIT);
}
if (player != nullptr) {
GameMessages::StartActivityTime startActivityTime;
startActivityTime.target = self->GetObjectID();
startActivityTime.startTime = state.TIME_LIMIT;
startActivityTime.Send(player->GetSystemAddress());
ActivityPause(self, player, false);
}
}
} else if (name.starts_with(EndWaveTimer)) { // called when a wave ends, contains the number of the next wave
if (state.GameStarted) {
state.WaveStatus = false;
// get rid of current spawns
TimerToggle(self);
// record the score
RecordPlayerWaveScore(self);
// get the wave number from the rest of the string, and store the next wave number
const auto waveNum = ShootingGallery::Logic::GetTimerNumber(name, EndWaveTimer).value_or(0) + 1;
state.ThisWave = waveNum;
// play wave animation on actors, cannon, and player
PlaySceneAnimation(self, "wave" + std::to_string(state.ThisWave), true, true, true);
// display wave number to player
DisplayWaveNumberToPlayer(self, waveNum);
// there are no more waves left so stop game after this wave
if (waveNum > g_const.NUM_WAVES()) {
// Game Over
ActivityTimerStart(self, GameOverTimer, 0.1f, 0.1f);
} else {
// setup next wave
ActivityTimerStart(self, SpawnWaveTimer + std::to_string(waveNum), g_const.IN_BETWEEN_WAVE_PAUSE, g_const.IN_BETWEEN_WAVE_PAUSE);
}
ActivityPause(self, GetActivityPlayer(self), true);
if (state.Super_Charge_Active && !state.Super_Charge_Paused) PauseChargeCannon(self);
}
} else if (name == GameOverTimer) {
// Send buffer timer here
auto* const player = GetActivityPlayer(self);
// The "cannonball" group: the cannon balls still in the air
const auto* const skill = self->GetComponent<SkillComponent>();
const auto cannonballs = skill != nullptr ? skill->GetManagedProjectileCount() : 0;
ActivityPause(self, player, true);
if (cannonballs >= 1) {
ActivityTimerStart(self, EndGameBufferTimer, 1, static_cast<float>(cannonballs));
} else {
RecordPlayerWaveScore(self);
StopGame(self, false);
}
TimerToggle(self);
} else if (name.starts_with(DoSpawnTimer)) {
if (state.GameStarted) {
// get the spawn number from the rest of the string
const auto spawnNum = ShootingGallery::Logic::GetTimerNumber(name, DoSpawnTimer);
if (spawnNum) DoSpawn(self, *spawnNum);
}
} else if (name == EndGameBufferTimer) {
RecordPlayerWaveScore(self);
StopGame(self, false);
}
}
// onActivityTimerDone's DoSpawn: load the spawn data's target at the first waypoint of its path
void ShootingGalleryCannon::DoSpawn(Entity* self, const uint32_t spawnNum) {
auto& state = GetState(self);
const auto itr = state.SPAWN_DATA.find(spawnNum);
if (itr == state.SPAWN_DATA.end()) return;
const auto spawnData = itr->second;
const auto templateID = spawnData.sdTemplate;
// get the position of the first waypoint (the Lua errors on a spawn without a path, which spawns nothing)
if (!spawnData.sdPath) return;
const auto* const path = Game::zoneManager->GetZone()->GetPath(*spawnData.sdPath);
if (path == nullptr || path->pathWaypoints.empty()) return;
EntityInfo info{};
info.lot = templateID;
info.spawnerID = self->GetObjectID();
info.pos = path->pathWaypoints.front().position;
info.settings.Insert<int32_t>(u"streakmod", GetConstants().STREAK_MOD);
info.settings.Insert<std::vector<int32_t>>(u"streakbonus", STREAK_BONUS);
info.settings.Insert<uint32_t>(u"wave", state.ThisWave);
info.settings.Insert<std::string>(u"custom_script_server", "scripts/ai/ACT/SG_TARGET.lua");
info.settings.Insert<std::string>(u"custom_script_client", "scripts/client/ai/SG_TARGET_CLIENT.lua");
// load the object in the world
auto* const child = Game::entityManager->CreateEntity(info, nullptr, self);
// onChildLoaded, before the clients get it so they get it on its path (live's targets came with their path)
OnChildLoaded(self, child);
if (auto* const simplePhysics = child->GetComponent<SimplePhysicsComponent>()) simplePhysics->SetPhysicsMotionState(4);
Game::entityManager->ConstructEntity(child);
}
// --------------------------------------------------------------
// onActivityNotify
// --------------------------------------------------------------
void ShootingGalleryCannon::OnActivityNotify(Entity* self, GameMessages::ActivityNotify& notify) {
auto& state = GetState(self);
const auto tKills = state.CannonBallKills;
const auto& g_const = GetConstants();
const auto itr = notify.notification.values.find(u"shot_done");
if (itr == notify.notification.values.end() || itr->second->GetValueType() != LDF_TYPE_S32) return;
// Don't count any of this if we're firing our super charged cannon ball
const LOT shotDone = static_cast<LDFData<int32_t>*>(itr->second.get())->GetValue();
if (tKills.empty() && shotDone != g_const.CANNON_SUPER_CHARGE) {
state.m_curStreak = 0;
// This account for real misses
state.m_misses++;
self->SetNetworkVar<bool>(u"HideStreak", true);
self->SetNetworkVar<bool>(u"UnMarkAll", true);
} else if (!tKills.empty()) {
// registerHit for all of the kills since last shot
for (const auto killID : tKills) {
// The Lua errors on a target that is gone
auto* const target = Game::entityManager->GetEntity(killID);
if (target != nullptr) RegisterHit(self, target, shotDone);
}
if (tKills.size() > 1) self->SetNetworkVar<bool>(u"mHit", true);
}
if (shotDone != g_const.CANNON_SUPER_CHARGE) {
if (state.friendly_hit) state.m_curStreak = 0;
UpdateStreak(self);
}
state.friendly_hit = false;
state.CannonBallKills.clear();
}
// registerHit
void ShootingGalleryCannon::RegisterHit(Entity* self, Entity* target, const LOT shotType) {
auto& state = GetState(self);
const auto& g_const = GetConstants();
int32_t points = SgTarget::GetActivityPoints(target);
// Only apply bonus to positive things and don't do streak etc for negative
if (points >= 0) {
points = ShootingGallery::Logic::ApplyStreakBonus(points, state.m_curStreak);
if (shotType != g_const.CANNON_SUPER_CHARGE) {
state.m_curStreak++;
if (state.m_curStreak > state.m_maxStreak) state.m_maxStreak = state.m_curStreak;
}
} else {
if (shotType != g_const.CANNON_SUPER_CHARGE) {
state.m_curStreak = 0;
// This accounts for friendlies
state.m_misses++;
state.friendly_hit = true;
}
self->SetNetworkVar<bool>(u"hitFriend", true);
}
auto* const user = GetActivityUser(self);
if (user != nullptr) {
GameMessages::NotifyClientShootingGalleryScore galleryScore;
galleryScore.target = self->GetObjectID();
galleryScore.score = points;
galleryScore.targetID = target->GetObjectID();
galleryScore.targetPos = target->GetPosition();
galleryScore.Send(user->GetSystemAddress());
}
state.m_totalScore += points;
self->SetNetworkVar<int32_t>(u"updateScore", state.m_totalScore);
const int32_t lastSuperTotal = state.LastSuperTotal.value_or(0);
const int32_t scScore = state.m_totalScore - lastSuperTotal;
if (shotType != g_const.CANNON_SUPER_CHARGE && scScore >= g_const.ChargedPoints && points >= 0) {
StartChargedCannon(self);
self->SetNetworkVar<float>(u"SuperChargeBar", 100.0f);
state.LastSuperTotal = state.m_totalScore;
}
float rewardF = 0.0f;
if (state.Matrix <= 5 && state.Matrix <= g_const.Score_Reward.size()) {
rewardF = ShootingGallery::Logic::GetRewardPercent(state.m_totalScore, g_const.Score_Reward[state.Matrix - 1]);
self->SetNetworkVar<float>(u"modelPercent", rewardF);
}
if (rewardF > 0 && rewardF < 200 && state.Matrix <= 5) {
const auto obj = Game::entityManager->GetEntitiesInGroup(g_const.Reward_Model_GrpName);
// check to make sure obj[1] is not nil
if (!obj.empty()) {
GameMessages::SpawnModelBricks spawnBricks;
spawnBricks.target = obj.front()->GetObjectID();
spawnBricks.amount = rewardF / 100.0f;
spawnBricks.position = target->GetPosition();
spawnBricks.Send(UNASSIGNED_SYSTEM_ADDRESS);
if (rewardF >= 100) {
SpawnNewModel(self);
state.Matrix++;
}
}
}
self->SetNetworkVar<std::u16string>(u"beatHighScore", GeneralUtils::to_u16string(state.m_totalScore));
CheckSpawn(self, target);
}
// onUpdateMissionTask: the cannon ball's kills, forwarded to the cannon; kept for the shot's end (onActivityNotify)
void ShootingGalleryCannon::UpdateMissionTaskKill(Entity* self, Entity* target) {
GetState(self).CannonBallKills.push_back(target->GetObjectID());
auto* const user = GetActivityUser(self);
if (user == nullptr) return;
if (auto* const missionComponent = user->GetComponent<MissionComponent>()) {
missionComponent->Progress(eMissionTaskType::SMASH, target->GetLOT(), self->GetObjectID());
}
}
// --------------------------------------------------------------
// RequestActivityEnter, then onRequestActivityEnter: put the player in the cannon, does not start the cannon
// --------------------------------------------------------------
void ShootingGalleryCannon::RequestActivityEnter(Entity* self, Entity* player) {
// The activity takes the player: the client enters the cannon
GameMessages::ActivityEnter activityEnter;
activityEnter.target = self->GetObjectID();
activityEnter.Send(player->GetSystemAddress());
if (auto* const shootingGallery = self->GetComponent<ShootingGalleryComponent>()) {
shootingGallery->SetCurrentPlayerID(player->GetObjectID());
Game::entityManager->SerializeEntity(self);
}
if (auto* const characterComponent = player->GetComponent<CharacterComponent>()) {
characterComponent->SetCurrentActivity(eGameActivity::SHOOTING_GALLERY);
if (auto* const possessor = player->GetComponent<PossessorComponent>()) {
possessor->SetPossessable(self->GetObjectID());
possessor->SetPossessableType(ePossessionType::NO_POSSESSION);
}
Game::entityManager->SerializeEntity(player);
}
// onRequestActivityEnter
GetState(self).activityPlayer = player->GetObjectID();
self->SetNetworkVar<bool>(u"HideScoreBoard", true);
self->SetNetworkVar<bool>(u"ReSetSuperCharge", true);
self->SetNetworkVar<bool>(u"showLoadingUI", true);
// Preloading reload animations: cannonballs, plunger, and pirate
const auto preload = [self](const Entity* object) {
GameMessages::PreloadAnimation preloadAnimation;
preloadAnimation.target = object->GetObjectID();
preloadAnimation.animationID = u"wave1";
preloadAnimation.respondObjID = self->GetObjectID();
preloadAnimation.Send(UNASSIGNED_SYSTEM_ADDRESS);
};
for (const auto* const sceneActor : Game::entityManager->GetEntitiesInGroup("cannongroup")) preload(sceneActor);
preload(player);
preload(self);
}
// spawnNewModel
void ShootingGalleryCannon::SpawnNewModel(Entity* self) {
auto& state = GetState(self);
const auto& g_const = GetConstants();
if (state.currentReward != LOT_NULL) {
if (!state.rewards.empty() && state.rewards.front() != LOT_NULL) {
state.rewards.push_back(state.currentReward);
} else {
state.rewards = { state.currentReward };
}
self->SetNetworkVar<int32_t>(u"rewardAdded", state.currentReward);
}
auto* const player = GetActivityPlayer(self);
// Score_LootMatrix_<Matrix> (none past the fifth)
const uint32_t lootMatrix = state.Matrix >= 1 && state.Matrix <= g_const.Score_LootMatrix.size() ? g_const.Score_LootMatrix[state.Matrix - 1] : 0;
for (auto* const rewardObj : Game::entityManager->GetEntitiesInGroup(g_const.Reward_Model_GrpName)) {
if (player == nullptr || lootMatrix == 0) continue;
const auto items = Loot::RollLootMatrix(player, lootMatrix);
for (const auto& [lot, count] : items) {
GameMessages::SetModelToBuild modelToBuild;
modelToBuild.target = rewardObj->GetObjectID();
modelToBuild.modelLot = lot;
modelToBuild.Send(UNASSIGNED_SYSTEM_ADDRESS);
state.currentReward = lot;
}
}
}
// --------------------------------------------------------------
// startGame: try to start the game
// --------------------------------------------------------------
void ShootingGalleryCannon::StartGame(Entity* self) {
auto& state = GetState(self);
// clear score
self->SetNetworkVar<uint32_t>(u"game_timelimit", static_cast<uint32_t>(state.TIME_LIMIT));
self->SetNetworkVar<bool>(u"Audio_Start_Intro", true);
state.currentReward = LOT_NULL;
for (auto* const rewardObj : Game::entityManager->GetEntitiesInGroup(GetConstants().Reward_Model_GrpName)) {
GameMessages::SetModelToBuild modelToBuild;
modelToBuild.target = rewardObj->GetObjectID();
modelToBuild.modelLot = LOT_NULL;
modelToBuild.Send(UNASSIGNED_SYSTEM_ADDRESS);
}
// get the player
auto* const player = GetActivityPlayer(self);
if (player != nullptr) {
// Tell the client to get the initial data for showing the top score
RequestActivitySummaryLeaderboardData(self);
// put the player in if we have to, otherwise start
const auto* const user = GetActivityUser(self);
if (user != nullptr && user->GetObjectID() == player->GetObjectID()) {
GameMessages::ActivityStart activityStart;
activityStart.target = self->GetObjectID();
activityStart.Send(player->GetSystemAddress());
}
self->SetNetworkVar<bool>(u"Clear", true);
DoGameStartup(self);
if (!state.firstTimeDone) {
// remove the activity cost from the player as they load into the map
TakeActivityCost(self, player->GetObjectID());
}
state.firstTimeDone = true;
}
SpawnNewModel(self);
}
// --------------------------------------------------------------
// stopGame: try to stop the game
// --------------------------------------------------------------
void ShootingGalleryCannon::StopGame(Entity* self, const bool bCanceling) {
auto& state = GetState(self);
self->SetNetworkVar<bool>(u"ReSetSuperCharge", true);
self->SetNetworkVar<bool>(u"HideSuper", true);
// get the player
auto* const player = GetActivityPlayer(self);
if (player == nullptr) return;
ToggleSuperCharge(self, false);
// if we have both stop it if we need to, but dont exit
if (!bCanceling) {
// Now retrieve everything from the cannon. We have the score here so we do the rest here too
const auto streak = state.m_maxStreak;
const auto misses = state.m_misses;
const auto fired = state.m_shotsFired;
// SetActivityUserData 0 / 1 / 2 and UpdateActivityLeaderboard: the leaderboard stores them
const float percentage = ShootingGallery::Logic::GetAccuracy(fired, misses);
SaveScore(self, player->GetObjectID(), static_cast<float>(state.m_totalScore), static_cast<float>(streak), percentage);
state.Mym_totalScore = state.m_totalScore;
state.m_totalScore = 0;
state.GameStarted = false;
ShowSummaryDialog(self, fired, fired - misses, streak);
AwardModels(state.rewards, player);
}
ActivityStop(self, player, false, bCanceling);
DoGameShutdown(self);
ResetVars(self);
}
// awardModels
void ShootingGalleryCannon::AwardModels(const std::vector<LOT>& rewards, Entity* player) {
auto* const inventory = player->GetComponent<InventoryComponent>();
if (inventory == nullptr) return;
for (const auto reward : rewards) {
if (reward != LOT_NULL) inventory->AddItem(reward, 1, eLootSourceType::ACTIVITY, eInventoryType::MODELS);
}
}
// DisplayWaveNumberToPlayer: the wave table {waveNum, waveStr} as wave.waveNum / wave.waveStr
void ShootingGalleryCannon::DisplayWaveNumberToPlayer(Entity* self, const uint32_t waveNum) {
if (GetActivityPlayer(self) == nullptr) return;
self->SetNetworkVar<uint32_t>(u"wave.waveNum", waveNum);
self->SetNetworkVar<uint32_t>(u"wave.waveStr", static_cast<uint32_t>(GetState(self).TIME_LIMIT));
}
// showSummaryDialog
void ShootingGalleryCannon::ShowSummaryDialog(Entity* self, const int32_t shots, const int32_t kills, const int32_t streak) {
auto& state = GetState(self);
if (GetActivityPlayer(self) == nullptr) return;
// The Lua also builds the activity reward's text (GetActivityReward) and sends none of it
const auto rscore = ShootingGallery::Logic::GetRewardsString(state.Mym_totalScore, state.PLAYER_SCORE, shots, kills, streak);
// Send the activity ID down to the client
self->SetNetworkVar<std::u16string>(u"UI_Rewards", GeneralUtils::ASCIIToUTF16(rscore));
self->SetNetworkVar<bool>(u"Audio_Final_Wave_Done", true);
RequestActivitySummaryLeaderboardData(self);
}
// RecordPlayerWaveScore
void ShootingGalleryCannon::RecordPlayerWaveScore(Entity* self) {
auto& state = GetState(self);
ShootingGallery::Logic::RecordPlayerWaveScore(state.PLAYER_SCORE, state.m_totalScore, state.ThisWave);
}
// onDoCalculateActivityRating
uint32_t ShootingGalleryCannon::CalculateActivityRating(Entity* self, const LWOOBJID playerID) {
// also return the score as the result for the activity
return static_cast<uint32_t>(std::max(GetState(self).Mym_totalScore, 0));
}
// checkSpawn
void ShootingGalleryCannon::CheckSpawn(Entity* self, Entity* target) {
auto& state = GetState(self);
const auto waveNum = state.ThisWave;
if (!state.GameStarted || waveNum == 0) return;
if (!target->HasVar(u"SpawnData")) return;
const auto& spawnData = target->GetVar<ShootingGallery::SpawnData>(u"SpawnData");
// spawn the right object
if (spawnData.sdRespawn && target->GetVar<uint32_t>(u"wave") == state.ThisWave && waveNum <= state.spawns.size()) {
auto& waveSpawns = state.spawns[waveNum - 1];
if (spawnData.sdnum >= waveSpawns.size()) return;
waveSpawns[spawnData.sdnum].sdLastPath = spawnData.sdPath;
SpawnObject(spawnData.sdnum, waveSpawns[spawnData.sdnum], self, false);
}
}
// RemovePlayerFromZone
void ShootingGalleryCannon::RemovePlayerFromZone(Entity* player) {
if (player == nullptr) return;
// TransferToLastNonInstance{bUseLastPosition = true}
auto* const character = player->GetCharacter();
auto* const characterComponent = player->GetComponent<CharacterComponent>();
if (character != nullptr && characterComponent != nullptr) characterComponent->SendToZone(character->GetLastNonInstanceZoneID());
}
// --------------------------------------------------------------
// onRequestActivityExit: User is exiting via cancel
// --------------------------------------------------------------
void ShootingGalleryCannon::OnRequestActivityExit(Entity* self, const LWOOBJID player, const bool canceled) {
if (canceled) {
StopGame(self, canceled);
RemovePlayerFromZone(Game::entityManager->GetEntity(player));
}
}
// --------------------------------------------------------------
// DoGameStartup: handle all the game startup data
// --------------------------------------------------------------
void ShootingGalleryCannon::DoGameStartup(Entity* self) {
auto& state = GetState(self);
// set game state and vars
ResetVars(self);
state.GameStarted = true;
self->SetNetworkVar<bool>(u"Clear", true);
// start the first wave
state.ThisWave = 1;
if (state.FIRST_WAVE_START_TIME < 1) state.FIRST_WAVE_START_TIME = 1;
ActivityTimerStart(self, SpawnWaveTimer + "1", state.FIRST_WAVE_START_TIME, state.FIRST_WAVE_START_TIME);
}
// --------------------------------------------------------------
// onChildLoaded: called when a Child is loaded
// --------------------------------------------------------------
void ShootingGalleryCannon::OnChildLoaded(Entity* self, Entity* child) {
// look through spawn data to find the most recent data that matches the template
auto* const spawnData = GetLatestSpawnDataByTemplate(self, child->GetLOT());
if (spawnData == nullptr) return;
auto& state = GetState(self);
const auto curSpawnNum = ++state.CurSpawnNum;
// store spawn for use later
state.spawnObject[curSpawnNum] = child->GetObjectID();
// store who the parent is
child->SetVar<LWOOBJID>(u"My_Parent_ID", self->GetObjectID());
// store the spawn data in the child
child->SetVar<ShootingGallery::SpawnData>(u"SpawnData", *spawnData);
// The cannon ball's kills (onUpdateMissionTask); a silent death is none
const auto selfID = self->GetObjectID();
const auto childID = child->GetObjectID();
child->AddDieCallback([this, selfID, childID]() {
auto* const cannon = Game::entityManager->GetEntity(selfID);
auto* const target = Game::entityManager->GetEntity(childID);
if (cannon != nullptr && target != nullptr && !SgTarget::DiedSilently(target)) UpdateMissionTaskKill(cannon, target);
});
const auto* const path = spawnData->sdPath ? Game::zoneManager->GetZone()->GetPath(*spawnData->sdPath) : nullptr;
if (path == nullptr || path->pathWaypoints.empty()) return;
if (spawnData->sdMovingPlat) {
// SetPathingSpeed: a moving platform has no handler for it. SetCurrentPath{pathName, startPoint = 0}
if (auto* const movingPlatform = child->GetComponent<MovingPlatformComponent>()) movingPlatform->SetCurrentPath(path->pathName, 0);
} else {
// assign child's waypoint
child->SetVar<std::string>(u"attached_path", path->pathName);
child->SetVar<uint32_t>(u"attached_path_start", 0);
child->SetPosition(path->pathWaypoints.front().position);
// start child on path
auto* movementAI = child->GetComponent<MovementAIComponent>();
if (movementAI == nullptr) movementAI = child->AddComponent<MovementAIComponent>(-1, MovementAIInfo{});
movementAI->SetHaltDistance(0.0f);
movementAI->SetPath(path->pathWaypoints);
movementAI->SetMaxSpeed(spawnData->sdSpeed);
movementAI->SetCurrentSpeed(spawnData->sdSpeed);
}
}
// IsValidActor: return if template is a valid actor
bool ShootingGalleryCannon::IsValidActor(const LOT templateID) const {
return std::ranges::find(VALID_ACTORS, templateID) != VALID_ACTORS.end();
}
// IsValidEffect: return if template is a valid effect
bool ShootingGalleryCannon::IsValidEffect(const LOT templateID) const {
return std::ranges::find(VALID_EFFECTS, templateID) != VALID_EFFECTS.end();
}
// DoGameShutdown: handle all the game shutdown data
void ShootingGalleryCannon::DoGameShutdown(Entity* self) {
GetState(self).GameStarted = false;
// cancel all timers
ActivityTimerStopAllTimers(self);
// despawn all spawns
DestroyAllSpawns(self);
}
// GetRandomPath
std::optional<std::string> ShootingGalleryCannon::GetRandomPath(Entity* self, const ShootingGallery::Spawn& spawn, const std::optional<std::string>& lastPath) {
auto& state = GetState(self);
const auto newPath = ShootingGallery::Logic::GetRandomPath(spawn.path, lastPath, state.lastRandomPath, RandomRange);
state.lastRandomPath = newPath;
return newPath;
}
// SpawnObject: spawn an object for the game
void ShootingGalleryCannon::SpawnObject(const uint32_t num, ShootingGallery::Spawn& spawn, Entity* self, const bool bSpawnNow) {
auto& state = GetState(self);
// get the current spawn number
const auto spawnNum = ++state.SpawnNum;
const auto newPath = GetRandomPath(self, spawn, spawn.sdLastPath);
// The spawn table keeps this for the rest of the cannon's life
if (!newPath) spawn.bRespawn = false;
// save the spawn data for the object when it is loaded
ShootingGallery::SpawnData spawnData;
spawnData.sdTemplate = spawn.id;
spawnData.sdRespawn = spawn.bRespawn;
spawnData.sdSpeed = spawn.speed;
spawnData.sdScore = spawn.score;
spawnData.sdPath = newPath;
spawnData.sdnum = num;
spawnData.sdChangeSpeed = spawn.bChangeSpeed;
spawnData.sdSpeedChance = spawn.speedChangeChance;
spawnData.sdMinSpeed = spawn.minSpeed;
spawnData.sdMaxSpeed = spawn.maxSpeed;
spawnData.sdMovingPlat = spawn.bMovingPlatform;
spawnData.sdDespawnTime = spawn.despawnTime;
spawnData.sdTimeScore = spawn.timeScore;
spawnData.bSpawned = false;
// store the data
state.SPAWN_DATA[spawnNum] = spawnData;
// set the timer to spawn the object
const auto spawnTime = ShootingGallery::Logic::GetSpawnTime(spawn, bSpawnNow, Random01());
if (spawnTime) ActivityTimerStart(self, DoSpawnTimer + std::to_string(spawnNum), *spawnTime, *spawnTime);
}
// DestroyAllSpawns
void ShootingGalleryCannon::DestroyAllSpawns(Entity* self) {
auto& state = GetState(self);
for (uint32_t spawn = 1; spawn <= state.CurSpawnNum; spawn++) {
const auto itr = state.spawnObject.find(spawn);
if (itr == state.spawnObject.end()) continue;
auto* const spawnObject = Game::entityManager->GetEntity(itr->second);
if (spawnObject == nullptr) continue;
const auto* const destroyable = spawnObject->GetComponent<DestroyableComponent>();
if (destroyable != nullptr && destroyable->GetIsDead()) continue;
// Die{killerID = spawnObject, killType = "SILENT"}
spawnObject->SetVar<bool>(u"SilentDeath", true);
spawnObject->Smash(spawnObject->GetObjectID(), eKillType::SILENT);
}
// reset vars
state.SpawnNum = 0;
state.CurSpawnNum = 0;
state.spawnObject.clear();
}
// GetLatestSpawnDataByTemplate: the newest spawn data not spawned yet that matches the template, or nullptr
ShootingGallery::SpawnData* ShootingGalleryCannon::GetLatestSpawnDataByTemplate(Entity* self, const LOT templateID) {
auto& state = GetState(self);
for (auto spawnNum = state.SpawnNum; spawnNum > 0; spawnNum--) {
const auto itr = state.SPAWN_DATA.find(spawnNum);
if (itr == state.SPAWN_DATA.end()) continue;
// check spawn flag and template
if (!itr->second.bSpawned && templateID == itr->second.sdTemplate) {
// set spawned flag
itr->second.bSpawned = true;
return &itr->second;
}
}
return nullptr;
}
// --------------------------------------------------------------
// notifyMessageBoxRespond: sent from a player when responding from a messagebox
// --------------------------------------------------------------
void ShootingGalleryCannon::NotifyMessageBoxRespond(Entity* self, Entity* sender, const int32_t iButton, const std::u16string& identifier) {
// make sure this is the right player
auto* const player = GetActivityPlayer(self);
if (player == nullptr || sender == nullptr || player->GetObjectID() != sender->GetObjectID()) return;
auto* const zoneControl = Game::entityManager->GetZoneControlEntity();
if (identifier == u"Scoreboardinfo") {
// show the summary message box
GameMessages::DisplayMessageBox messageBox;
messageBox.target = player->GetObjectID();
messageBox.bShow = true;
messageBox.imageID = 2;
messageBox.callbackClient = zoneControl != nullptr ? zoneControl->GetObjectID() : LWOOBJID_EMPTY;
messageBox.text = u"Retry?";
messageBox.identifier = u"Shooting_Gallery_Retry";
messageBox.Send(player->GetSystemAddress());
} else {
const bool retry = identifier == u"Shooting_Gallery_Retry" || identifier == u"RePlay";
// User wants to retry or is closing the big help to start the game (any button 0 is that too)
if ((iButton == 1 && retry) || identifier == u"SG1" || iButton == 0) {
self->SetNetworkVar<bool>(u"Clear", true);
StartGame(self);
} else if (iButton == 0 && retry) { // User wants to quit (never reached: button 0 started the game above)
self->RequestActivityExit(self, player->GetObjectID(), false);
RemovePlayerFromZone(player);
} else if (iButton == 1 && identifier == u"Shooting_Gallery_Exit") {
RemovePlayerFromZone(player);
self->RequestActivityExit(self, player->GetObjectID(), true);
}
}
}
// notifyObjectLoaded
void ShootingGalleryCannon::NotifyObjectLoaded(Entity* self, const LWOOBJID objectID, const LOT templateID) {
auto& state = GetState(self);
if (IsValidActor(templateID)) {
// store the actor
state.ACTORS.push_back(objectID);
} else if (IsValidEffect(templateID)) { // check for effects
state.EFFECTS.push_back(objectID);
}
}
// onNotifyObject
void ShootingGalleryCannon::OnNotifyObject(Entity* self, Entity* sender, const std::string& name, int32_t param1, int32_t param2) {
if (name == "FinishedPath" && sender != nullptr) OnTargetFinishedPath(self, sender);
}
void ShootingGalleryCannon::OnTargetFinishedPath(Entity* self, Entity* target) {
CheckSpawn(self, target);
}
// notifyActivityStateChangeRequest
void ShootingGalleryCannon::NotifyActivityStateChangeRequest(Entity* self, const int32_t iNumValue1) {
if (iNumValue1 == 1000) { // retry
StartGame(self);
} else if (iNumValue1 == 7777) { // query
RequestActivitySummaryLeaderboardData(self);
} else if (iNumValue1 == 2000) { // exit
auto* const player = GetActivityPlayer(self);
if (player == nullptr) return;
auto* const zoneControl = Game::entityManager->GetZoneControlEntity();
// show the summary message box
GameMessages::DisplayMessageBox messageBox;
messageBox.target = player->GetObjectID();
messageBox.bShow = true;
messageBox.imageID = 1;
messageBox.callbackClient = zoneControl != nullptr ? zoneControl->GetObjectID() : LWOOBJID_EMPTY;
messageBox.text = u"Exit?";
messageBox.identifier = u"Shooting_Gallery_Exit";
messageBox.Send(player->GetSystemAddress());
} else if (iNumValue1 == 1200) { // play
StartGame(self);
}
}