StatisticsController - alexneargarder/Broforce-Docs GitHub Wiki
StatisticsController
Table of Contents
- Unity Lifecycle & Setup
- Networking & RPC
- Statistics Tracking System
- Methods
- CacheStats
- CalcAndSubmitCampaignScore
- CalculateTotalTime
- ClearCachedStats
- GetCampaignTotalBrotality
- GetCampaignTotalTime
- GetDeathsCount
- GetTime
- GetTimeString
- GetTimeString
- LogLevelScore
- NotifyBlockDestroyed
- NotifyKnifedMook
- NotifyLevelFinished
- NotifyLevelLoaded
- NotifyMookDeath
- NotifyMookHeardSound
- NotifyMookSeenBro
- NotifyMookTryShootAtBBro
- NotifyRescue
- NotifyTankDeath
- NotifyTruckDeath
- RegisterMook
- RegisterRescueBro
- ResetScore
- SetTotalTime
- Fields
- Methods
- Brutality Scoring System
- Death Recording System
- Deathmatch Statistics
- Campaign Progress System
Unity Lifecycle & Setup
Methods
private void Awake()
Initializes the singleton instance and creates a new LevelStats object for tracking current level statistics. Sets initial destruction count to 0.
internal static void NotifyPause(bool paused)
Handles pause state notifications for time tracking. Records pause start time when paused. Placeholder for pause duration calculation when unpaused (currently unused).
Parameters:
- bool paused: True when game is paused, false when resumed
private void NotOnGUI()
Debug GUI display method (despite misleading name). Shows current level statistics including destruction count, kills/total enemies, formatted time, rescues/cages, brutality score, and brutality meter with scrollbar. Not actually disabled.
private void Start()
Initializes statistics tracking for the level start. Resets elapsed time to 0, sets brutality and time percentiles to -1, initializes brutality grace period to 6 seconds, resets brutality level to 0, and loads existing campaign brutality totals if brutality scoring is enabled for the current campaign.
Fields
private float pauseTime = -1f
Tracks the timestamp when the game was paused. Set to current Time.time when paused, used for pause duration tracking. Initialized to -1f indicating no pause has occurred yet.
Networking & RPC
Methods
public virtual void DeserializeStats(byte[] byteStream)
Deserializes received statistics data from network. Unpacks byte stream to populate current stats including all kill/alert counters, elapsed time, and level attempts. Creates new LevelStats if needed.
Parameters:
- byte[] byteStream: The serialized statistics data to unpack
public override UnityStream PackState(UnityStream stream)
Packs the current elapsed time into a network stream for multiplayer synchronization
Parameters:
- UnityStream stream: The Unity network stream to serialize data to
Returns:
UnityStream
: The modified stream after serialization
public virtual byte[] SerializeStats()
Serializes current level statistics for network transmission. Packs destruction, kills, rescues, alert states, knife kills, unaware kills, elapsed time, and level attempts into byte array. Uses current stats or falls back to last level stats.
Returns:
byte[]
: Serialized statistics data as byte array
public override UnityStream UnpackState(UnityStream stream)
Unpacks elapsed time from a network stream during multiplayer synchronization
Parameters:
- UnityStream stream: The Unity network stream to deserialize data from
Returns:
UnityStream
: The stream after deserialization
Statistics Tracking System
Methods
public static void CacheStats()
Caches the current level statistics for later aggregation (used by super checkpoints). If no cached stats exist, stores the current stats directly. If cached stats already exist, adds the current stats to them. Creates a new empty LevelStats object for continued tracking.
internal static void CalcAndSubmitCampaignScore()
Calculates total campaign statistics and submits them to leaderboards. Iterates through all level scores to sum brutality and time, then submits to Playtomic if using Badumna connection. Called at campaign completion.
public static void CalculateTotalTime()
Calculates and synchronizes the total elapsed time across all players. Gets time from current or last level stats and sends RPC to all players if host. Ensures consistent time tracking in multiplayer.
public static void ClearCachedStats()
Clears the cached statistics buffer. Used to reset temporary stats storage between level attempts or when starting fresh.
public static long GetCampaignTotalBrotality()
Calculates and returns the total brutality score across all campaign levels. Sums calculated brutality values from each level's statistics. Also builds debug string with detailed breakdowns (unused).
Returns:
long
: Total brutality score for the entire campaign
public static float GetCampaignTotalTime()
Calculates and returns the total time spent across all campaign levels. Iterates through campaign score dictionary summing elapsed times. Also builds detailed debug string with per-level statistics (unused).
Returns:
float
: Total elapsed time across all completed campaign levels
public static int GetDeathsCount()
Returns the total number of recorded deaths from the last completed level's death list.
Returns:
int
: The count of death objects in the last level's death list
public static float GetTime()
Gets the elapsed time from the last completed level's statistics.
Returns:
float
: The elapsed time in seconds from the last level stats
public static string GetTimeString(float time)
Converts the current level's elapsed time into a formatted time string in MM:SS.T format (where T is tenths of seconds).
Returns:
string
: Formatted time string showing minutes, seconds, and tenths
public static string GetTimeString(float time)
Converts a time value in seconds to a formatted string in MM:SS.T format (where T is tenths of seconds).
Parameters:
- float time: Time in seconds to format
Returns:
string
: Formatted time string showing minutes, seconds, and tenths
private static void LogLevelScore(int levelNum, float time, long brotality, long stealth, int kills, int levelAttempts)
Stores level statistics in the campaign score dictionary. Creates the dictionary if needed and replaces existing scores for the same level number. Used internally after level completion.
Parameters:
- int levelNum: The level number identifier
- float time: Time taken to complete the level
- long brotality: Brutality score (unused in current implementation)
- long stealth: Stealth score (unused in current implementation)
- int kills: Number of enemies killed
- int levelAttempts: Number of attempts to complete the level
public static void NotifyBlockDestroyed(Block block)
Records terrain destruction for brutality scoring. Called when any block is destroyed. Adds 0.1 to totalBrotality and increments destruction counter.
Parameters:
- Block block: The block that was destroyed
public static void NotifyKnifedMook(Mook mook)
Records when a mook is killed by a knife attack. Called from mook damage handling when death is caused by knife damage type. Increments the mooksKnifed statistic for stealth tracking.
Parameters:
- Mook mook: The mook that was knifed
public static void NotifyLevelFinished(LevelResult result)
Handles all statistics processing when a level ends. Records death counts by hero/mook type for campaign tracking, merges cached stats on success, calculates stealth score, logs level score to campaign dictionary, and resets or increments level attempts based on result.
Parameters:
- LevelResult result: Whether the level was completed successfully or failed
public static void NotifyLevelLoaded()
Records the total number of mooks at level start by storing the current totalMooks count. Called when a level finishes loading to establish the baseline mook count for completion percentage tracking.
public static void NotifyMookDeath(Mook mook)
Records a mook death for statistics tracking. Increments kill count, updates brutality score based on kill timing (combo multiplier if kills within 0.5 seconds), sets brutality grace periods, adds 1 brutality point and 1 music intensity, updates last kill time, and tracks stealth kills if the mook was unaware.
Parameters:
- Mook mook: The mook that died
public static void NotifyMookHeardSound(Mook mook)
Increments the count of mooks that have heard suspicious sounds. Only counts living mooks that can be added to statistics.
Parameters:
- Mook mook: The mook that heard a sound
public static void NotifyMookSeenBro(Mook mook)
Notifies the statistics system when a mook has seen a bro (player). Called when AI becomes aware of player presence. Increments the mooksHalfAlerted counter if conditions are met.
Parameters:
- Mook mook: The mook that has spotted a bro
public static void NotifyMookTryShootAtBBro(Mook mook)
Records when a mook attempts to shoot at a bro. Called by enemy AI when entering shooting state. Increments mooksFullyAlerted to track complete enemy awareness.
Parameters:
- Mook mook: The mook attempting to shoot
public static void NotifyRescue()
Records a prisoner rescue event. Adds 3 brutality points, sets grace period based on current brutality level (unused grace calculation), and increments rescue counter. Called when players free prisoners from cages.
public static void NotifyTankDeath(Tank tank)
Records a tank death for statistics and world map campaign tracking. Updates vehicle death counters in world map saves, sets last kill time, adds 10 brutality points and 4 music intensity, and sets brutality grace period to 5 seconds (then immediately to 1 second). Tracks as vehicle type in campaign statistics.
Parameters:
- Tank tank: The tank that was destroyed
public static void NotifyTruckDeath(Tank tank)
Records a truck death for statistics and world map campaign tracking. Updates vehicle death counters in world map saves, sets last kill time, adds 5 brutality points and 3 music intensity, and sets brutality grace period to 4 seconds (then immediately to 1 second). Tracks as vehicle type in campaign statistics.
Parameters:
- Tank tank: The truck (Tank instance) that was destroyed
public static void RegisterMook(Mook mook)
Registers a mook as part of the level's total mook count for statistics tracking. Only counts mooks that return true from CanAddToStatistics().
Parameters:
- Mook mook: The mook instance to register for statistics tracking
public static void RegisterRescueBro()
Increments the total cage/rescue count for the current level statistics. Called when a bro rescue cage is discovered in the level.
internal static void ResetScore()
Resets all campaign scoring data. Clears the campaign score dictionary and deathmatch death objects. Called when starting a new campaign or resetting progress.
private static void SetTotalTime(float totatTime)
RPC method that sets the synchronized total time value. Called by host to update all players' elapsed time. Updates currentStats.elapsedTime if stats exist.
Parameters:
- float totatTime: The synchronized total time value
Fields
public static LevelStats cachedStats
Temporary storage for statistics during level transitions or checkpoints
public LevelStats currentStats
Active statistics being tracked for the current level in progress
public static int efficiencyScore
Score based on completion efficiency (unused in current implementation)
public static int killScore
Score points awarded for kills (unused in current implementation)
public LevelStats lastLevelStats
Statistics from the most recently completed level
public static int rescueScore
Score points awarded for rescuing bros (unused in current implementation)
private static int totalMooks
Running count of total mooks spawned across all levels in the current session
Brutality Scoring System
Methods
public static void AddBrotality(int extra)
Adds points to the brutality score and music intensity. Adds the specified amount to totalBrotality and musicIntensity. Sets grace period to 1 second (5+ points) or extends existing grace if less than 1 second (under 5 points).
Parameters:
- int extra: The amount of brutality points to add
public static void AddBrotalityGrace(float grace)
Extends the brutality grace period timer. Sets grace period to the specified value if greater than current. Grace period prevents brutality score decay temporarily after actions.
Parameters:
- float grace: The grace period duration in seconds to potentially set
public static long CalculateBrotality(LevelStats stats)
Calculates the final brutality score from level statistics. Subtracts penalties from total, multiplies by 10, rounds up, then multiplies by 10 again. Ensures scores are rounded to nearest 100.
Parameters:
- LevelStats stats: The level statistics to calculate brutality from
Returns:
long
: Final brutality score as a long value
public static void CalculateBrotalityLevel(float brotalityValue)
Determines brutality level based on current score value. Sets level 0-5 based on thresholds: 0 (≤12), 1 (≤37), 2 (≤87), 3 (≤162), 4 (≤362), 5 (>362). Updates static brotalityLevel field.
Parameters:
- float brotalityValue: The current brutality score to evaluate
private void CalculateStealth()
Placeholder method for stealth score calculation. Currently empty - stealth scoring system not implemented. Intended to evaluate undetected kills and silent progression.
public static int GetBrotalityLevel()
Returns the current brutality level (0-5). Level determines score decay rate and visual feedback intensity. Static accessor for the private brotalityLevel field.
Returns:
int
: Current brutality level from 0 (lowest) to 5 (highest)
public static float GetBrotalometerValue()
Gets the current brutality meter value, which represents total brutality minus penalties.
Returns:
float
: The current brutality meter value as displayed on the HUD
public static float GetMusicIntensity()
Gets the current music intensity value that drives dynamic music changes based on combat action. Increased by kills and decreased over time when not in combat.
Returns:
float
: The current music intensity value
public static void NotifyCaptureCheckPoint()
Awards brutality bonus for capturing a checkpoint. Adds 3 brutality points and sets brutality grace period to 5 seconds (then immediately to 1 second). Does nothing if level is already finished.
public static bool ShowBrotalityScore()
Determines whether brutality score should be displayed based on current campaign settings. Returns true only if a campaign is loaded with a header that has brutality scoreboard enabled and the game is not in edit mode.
Returns:
bool
: True if brutality score should be shown, false otherwise
private void Update()
Unity Update method that manages brutality scoring mechanics. Handles grace period countdown, brutality decay rates based on level (3-50 per second), applies decay multipliers for extended inactivity (up to 3x), manages music intensity fadeout, calculates brutality meter display value, updates brutality level thresholds, and tracks elapsed time when unpaused.
Fields
private float brotalitometerValue
Current visual fill level of the brutality meter UI (unused)
public const float brotalityFifthBarValue = 200f
Deprecated constant that was likely used for visual brutality bar display. Value of 200f represents the fifth threshold level. No longer used in current implementation.
public const float brotalityFirstBarValue = 12f
Brutality score threshold for filling the first bar of the brutality meter (12 points)
public const float brotalityFourthBarValue = 75f
Deprecated constant that was likely used for visual brutality bar display. Value of 75f represents the fourth threshold level. No longer used in current implementation.
protected float brotalityGrace
Grace period timer for maintaining brutality multiplier chains (unused)
public static int brotalityLevel
Tracks the current brutality level (0-5) based on brotalitometerValue thresholds. Used by UI elements like MookAlertLevelIndicator to display alert icons. Level 0: <=12, Level 1: <=37, Level 2: <=87, Level 3: <=162, Level 4: <=362, Level 5: >362. Reset to 0 at level start.
public const float brotalitySecondBarValue = 25f
Deprecated constant that was likely used for visual brutality bar display. Value of 25f represents the second threshold level. No longer used in current implementation.
public const float brotalityThirdBarValue = 50f
Deprecated constant that was likely used for visual brutality bar display. Value of 50f represents the third threshold level. No longer used in current implementation.
protected int lastBrotality
Previous brutality score value (unused in current implementation)
protected float lastKillTime
Timestamp of the most recent kill, used for brutality multiplier timing
private float musicIntensity
Music intensity level based on recent player actions (unused)
Death Recording System
Methods
public static void AddToDeathList(DeathObject deathObj)
Adds a death object to the current level's death list if it doesn't already exist. Checks for null objects and validates that statistics tracking is initialized. Prevents duplicate entries by checking if a death with the same unit ID already exists.
Parameters:
- DeathObject deathObj: The death object to add to the tracking list
public static void AddToDeathListRPC(NID nid, DeathType deathType, HeroType mookType, float xI, float yI)
RPC method that creates and adds a mook death object to the current level's death list. Called on all clients to synchronize death tracking.
Parameters:
- NID nid: Network ID of the unit that died
- DeathType deathType: The type/cause of death
- MookType mookType: The type of mook that died
- float xI: X position where death occurred
- float yI: Y position where death occurred
public static void AddToDeathListRPC(NID nid, DeathType deathType, HeroType mookType, float xI, float yI)
RPC method that creates and adds a hero death object to the current level's death list. Called on all clients to synchronize death tracking.
Parameters:
- NID nid: Network ID of the hero that died
- DeathType deathType: The type/cause of death
- HeroType mookType: The type of hero that died (parameter name is legacy)
- float xI: X position where death occurred
- float yI: Y position where death occurred
public static DeathObject GetDeathObject(int deathIndex)
Retrieves a specific death object from the last level's death list by index. Used by the level over screen to display death replay information.
Parameters:
- int deathIndex: The index of the death object to retrieve
Returns:
DeathObject
: The DeathObject at the specified index, or null if index is out of bounds
public static void NotifyDeathType(NID nid, MookType mookType, DeathType deathType, float xI, float yI)
Records and broadcasts a death event to all players via RPC. Only processes non-None and non-Unassigned death types when the level is not finished. Sends death information including unit ID, type, death cause, and position.
Parameters:
- NID nid: Network ID of the unit that died
- MookType mookType: The type of mook that died
- DeathType deathType: The type/cause of death
- float xI: X position where death occurred
- float yI: Y position where death occurred
public static void NotifyMookDeathType(TestVanDammeAnim vanDamme, DeathType deathType)
Records and broadcasts a mook death with specific death type to all players via RPC. Extracts mook properties (ID, type, position) and sends death notification if death type is valid and level is not finished.
Parameters:
- Mook mook: The mook that died
- DeathType deathType: The type/cause of death
public static void NotifyMookDeathType(TestVanDammeAnim vanDamme, DeathType deathType)
Records and broadcasts a hero (bro) death with specific death type to all players via RPC. Extracts hero properties (ID, type, position) and sends death notification if death type is valid and level is not finished.
Parameters:
- TestVanDammeAnim vanDamme: The hero/bro that died
- DeathType deathType: The type/cause of death
Deathmatch Statistics
Methods
internal static void AddDeathmatchDeathObject(int killer, DeathObject deathObject)
Records a death event in deathmatch mode, tracking which player scored the kill
Parameters:
- int killer: The player index who scored the kill (0-3)
- DeathObject deathObject: The death object containing information about the death event
internal static void ClearDeathmatchDeathObjects()
Clears all recorded deathmatch kills for all players
internal static List<DeathObject> GetDeathmatchKillObjects(int player)
Retrieves all death objects (kills) recorded for a specific player in deathmatch
Parameters:
- int player: The player index (0-3) to get kills for
Returns:
List<DeathObject>
: List of death objects representing kills by this player, or null if no data exists
Campaign Progress System
Fields
public static float brotalityPercentile
The percentile ranking for brutality score (0-100, where 0 means top percentile)
public static int brotalityRank
The player's global rank for brutality score on the current campaign leaderboard
private static int levelAttempts
Tracks the number of attempts made on the current level before successful completion
public static float stealthPercentile
The percentile ranking for stealth score (0-100, where 0 means top percentile)
public static int stealthRank
The player's global rank for stealth score on the current campaign leaderboard
public static float timePercentile
The percentile ranking for completion time (0-100, where 0 means top percentile)
public static int timeRank
The player's global rank for completion time on the current campaign leaderboard