Skip to content

Commit

Permalink
refactor: simplify RegisterHUDPanelForGamemode, pull in Peen's usages
Browse files Browse the repository at this point in the history
  • Loading branch information
tsa96 authored and PeenScreeker committed Sep 8, 2024
1 parent 1182066 commit b46c6b5
Show file tree
Hide file tree
Showing 6 changed files with 85 additions and 61 deletions.
22 changes: 17 additions & 5 deletions scripts/hud/df-jump.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import { PanelHandler } from 'util/module-helpers';
import { RegisterHUDPanelForGamemode } from 'util/register-for-gamemodes';
import { GamemodeCategories, GamemodeCategory } from 'common/web';

enum ColorClass {
AIR = 'dfjump__press--air',
Expand All @@ -22,11 +24,21 @@ class DFJumpHandler {
inverseMaxDelay: float;

constructor() {
$.RegisterForUnhandledEvent('LevelInitPostEntity', () => this.onMapInit());
$.RegisterEventHandler('DFJumpDataUpdate', this.panels.container, (releaseDelay, pressDelay, totalDelay) =>
this.onDFJumpUpdate(releaseDelay, pressDelay, totalDelay)
);
$.RegisterForUnhandledEvent('DFJumpMaxDelayChanged', (newDelay: float) => this.setMaxDelay(newDelay));
RegisterHUDPanelForGamemode({
gamemodes: GamemodeCategories.get(GamemodeCategory.DEFRAG),
onLoad: () => this.onMapInit(),
events: [
{
event: 'DFJumpDataUpdate',
callback: (releaseDelay, pressDelay, totalDelay) =>
this.onDFJumpUpdate(releaseDelay, pressDelay, totalDelay)
},
{
event: 'DFJumpMaxDelayChanged',
callback: (newDelay) => this.setMaxDelay(newDelay)
}
]
});
}

onMapInit() {
Expand Down
13 changes: 10 additions & 3 deletions scripts/hud/ground-boost.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { PanelHandler } from 'util/module-helpers';
import { magnitude2D } from 'util/math';
import { RegisterHUDPanelForGamemode } from 'util/register-for-gamemodes';
import { GamemodeCategories, GamemodeCategory } from 'common/web';

enum TimerFlags {
NONE = 0,
Expand Down Expand Up @@ -45,9 +47,14 @@ class GroundboostHandler {
textColorMode: number;

constructor() {
$.RegisterForUnhandledEvent('HudProcessInput', () => this.onHudUpdate());
$.RegisterForUnhandledEvent('LevelInitPostEntity', () => this.onMapInit());
$.RegisterForUnhandledEvent('OnDefragHUDGroundboostChange', () => this.onConfigChange());
RegisterHUDPanelForGamemode({
gamemodes: GamemodeCategories.get(GamemodeCategory.DEFRAG),
onLoad: () => this.onMapInit(),
events: [
{ event: 'HudProcessInput', callback: () => this.onHudUpdate() },
{ event: 'OnDefragHUDGroundboostChange', callback: () => this.onConfigChange() }
]
});
}

onMapInit() {
Expand Down
17 changes: 11 additions & 6 deletions scripts/hud/jump-stats.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import { PanelHandler } from 'util/module-helpers';
import { RegisterHUDPanelForGamemode } from '../util/register-for-gamemodes';
import { GamemodeCategories, GamemodeCategory } from '../common/web';

@PanelHandler()
class JumpStatsHandler {
Expand All @@ -25,9 +27,12 @@ class JumpStatsHandler {
efficiencyBuffer: string[];

constructor() {
$.RegisterForUnhandledEvent('LevelInitPostEntity', () => this.onMapInit());
$.RegisterEventHandler('OnJumpStarted', this.panels.container, () => this.onJump());
$.RegisterForUnhandledEvent('OnJumpStatsCFGChange', () => this.onConfigChange());
RegisterHUDPanelForGamemode({
gamemodes: GamemodeCategories.get(GamemodeCategory.BHOP),
onLoad: () => this.onMapInit(),
handledEvents: [{ event: 'OnJumpStarted', panel: this.panels.container, callback: () => this.onJump() }],
events: [{ event: 'OnJumpStatsCFGChange', callback: () => this.onConfigChange() }]
});
}

onJump() {
Expand Down Expand Up @@ -66,7 +71,7 @@ class JumpStatsHandler {
this.addToBuffer(this.speedDeltaBuffer, lastJumpStats.jumpSpeedDelta.toFixed(0));
this.addToBuffer(this.takeoffTimeBuffer, this.makeTime(lastJumpStats.takeoffTime));
this.addToBuffer(this.timeDeltaBuffer, lastJumpStats.timeDelta.toFixed(3));
this.addToBuffer(this.strafesBuffer, lastJumpStats.strafeCount);
this.addToBuffer(this.strafesBuffer, lastJumpStats.strafeCount.toFixed(0));
this.addToBuffer(this.syncBuffer, this.makePercentage(lastJumpStats.strafeSync));
this.addToBuffer(this.gainBuffer, this.makePercentage(lastJumpStats.speedGain));
this.addToBuffer(this.yawRatioBuffer, this.makePercentage(lastJumpStats.yawRatio));
Expand All @@ -87,9 +92,9 @@ class JumpStatsHandler {
return buffer;
}

addToBuffer(buffer: string[], value: string | number) {
addToBuffer(buffer: string[], value: string) {
buffer[buffer.length - 1] += '\n';
buffer.push(value.toString());
buffer.push(value);

if (buffer.length > this.bufferLength) buffer.shift();
}
Expand Down
4 changes: 1 addition & 3 deletions scripts/hud/powerup-timer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,7 @@ class PowerupTimerHandler {
constructor() {
RegisterHUDPanelForGamemode({
gamemodes: GamemodeCategories.get(GamemodeCategory.DEFRAG),
context: this,
contextPanel: $.GetContextPanel(),
handledEvents: [{ event: 'HudProcessInput', contextPanel: $.GetContextPanel(), callback: this.onUpdate }]
events: [{ event: 'HudProcessInput', callback: () => this.onUpdate() }]
});
}

Expand Down
35 changes: 21 additions & 14 deletions scripts/hud/synchronizer.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import { PanelHandler } from 'util/module-helpers';
import * as MomMath from 'util/math';
import { rgbaStringLerp } from 'util/colors';
import { RegisterHUDPanelForGamemode } from '../util/register-for-gamemodes';
import { Gamemode } from '../common/web';

const Colors = {
EXTRA: ['rgba(24, 150, 211, 1)', 'rgba(87, 200, 255, 1)'],
Expand Down Expand Up @@ -74,20 +76,25 @@ class Synchronizer {
}

constructor() {
$.RegisterEventHandler('HudProcessInput', $.GetContextPanel(), () => this.onUpdate());

$.RegisterForUnhandledEvent('OnSynchroModeChanged', (cvarValue) => this.setDisplayMode(cvarValue));
$.RegisterForUnhandledEvent('OnSynchroColorModeChanged', (cvarValue) => this.setColorMode(cvarValue === 1));
$.RegisterForUnhandledEvent('OnSynchroDynamicModeChanged', (cvarValue) => this.setDynamicMode(cvarValue === 1));
$.RegisterForUnhandledEvent('OnSynchroDirectionChanged', (cvarValue) => this.setDirection(cvarValue === 1));
$.RegisterForUnhandledEvent('OnSynchroBufferChanged', (cvarValue) => this.setBufferLength(cvarValue));
$.RegisterForUnhandledEvent('OnSynchroMinSpeedChanged', (cvarValue) => this.setMinSpeed(cvarValue));
$.RegisterForUnhandledEvent('OnSynchroStatModeChanged', (cvarValue) => this.setStatMode(cvarValue));
$.RegisterForUnhandledEvent('OnSynchroStatColorModeChanged', (cvarValue) =>
this.setStatColorMode(cvarValue === 1)
);
$.RegisterForUnhandledEvent('OnJumpStarted', () => this.onJump());
$.RegisterForUnhandledEvent('LevelInitPostEntity', () => this.onLoad());
RegisterHUDPanelForGamemode({
gamemodes: [Gamemode.BHOP, Gamemode.SURF, Gamemode.CLIMB_KZT, Gamemode.CLIMB_MOM],
onLoad: () => this.onLoad(),
events: [
{ event: 'HudProcessInput', callback: () => this.onUpdate() },
{ event: 'OnJumpStarted', callback: () => this.onJump() },
{ event: 'OnSynchroModeChanged', callback: (cvarValue) => this.setDisplayMode(cvarValue) },
{ event: 'OnSynchroColorModeChanged', callback: (cvarValue) => this.setColorMode(cvarValue === 1) },
{ event: 'OnSynchroDynamicModeChanged', callback: (cvarValue) => this.setDynamicMode(cvarValue === 1) },
{ event: 'OnSynchroDirectionChanged', callback: (cvarValue) => this.setDirection(cvarValue === 1) },
{ event: 'OnSynchroBufferChanged', callback: (cvarValue) => this.setBufferLength(cvarValue) },
{ event: 'OnSynchroMinSpeedChanged', callback: (cvarValue) => this.setMinSpeed(cvarValue) },
{ event: 'OnSynchroStatModeChanged', callback: (cvarValue) => this.setStatMode(cvarValue) },
{
event: 'OnSynchroStatColorModeChanged',
callback: (cvarValue) => this.setStatColorMode(cvarValue === 1)
}
]
});
}

onLoad() {
Expand Down
55 changes: 25 additions & 30 deletions scripts/util/register-for-gamemodes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,42 +21,42 @@
* ```
* @param gamemodes - Gamemodes to register the callback for. Handler is unregistered for any other modes.
* @param event - Event name
* @param context - Panel context
* @param panel - Panel context
* @param callbackFn - Event callback
* @returns Cleanup function that unregisters both event handlers
*/
export function RegisterEventForGamemodes(
gamemodes: number[],
event: keyof GlobalEventNameMap,
context: GenericPanel,
panel: GenericPanel,
callbackFn: (...args: unknown[]) => void
): () => void {
let innerHandle: uuid | undefined;
const outerHandle = $.RegisterForUnhandledEvent('LevelInitPostEntity', () => {
if (!innerHandle && gamemodes.includes(GameModeAPI.GetCurrentGameMode())) {
innerHandle = $.RegisterEventHandler(event, context, callbackFn);
innerHandle = $.RegisterEventHandler(event, panel, callbackFn);
} else if (innerHandle) {
$.UnregisterEventHandler(event, context, innerHandle);
$.UnregisterEventHandler(event, panel, innerHandle);
innerHandle = undefined;
}
});

return () => {
if (innerHandle) {
$.UnregisterEventHandler(event, context, innerHandle);
$.UnregisterEventHandler(event, panel, innerHandle);
}

$.UnregisterForUnhandledEvent('LevelInitPostEntity', outerHandle);
};
}

// Could do RegisterUnhandledEventForGamemodes, just don't have a use for it.

export interface RegisterHUDPanelForGamemodeOptions {
context: object;
contextPanel: Panel;
gamemodes: number[];
onLoad?: Func;
handledEvents?: Array<{ event: keyof GlobalEventNameMap; callback: Func; contextPanel: Panel }>;
unhandledEvents?: Array<{ event: keyof GlobalEventNameMap; callback: Func }>;
handledEvents?: Array<{ event: keyof GlobalEventNameMap; panel: GenericPanel; callback: Func }>;
events?: Array<{ event: keyof GlobalEventNameMap; callback: Func }>;
}

/**
Expand All @@ -67,7 +67,7 @@ export interface RegisterHUDPanelForGamemodeOptions {
* Any events provided will be registered at `LevelInitPostEntity` when the given a map is launched in the provided
* modes, and unregistered in any other modes.
*
* An optional `onLoad` function will be called whenever a launched in the provided modes.
* An optional `onLoad` function will be called whenever a map is loaded in the provided modes.
*
* You must provide the current JS context with `context`, and don't need to use `.bind(this)` on any functions you pass.
*
Expand All @@ -77,7 +77,6 @@ export interface RegisterHUDPanelForGamemodeOptions {
* static {
* RegisterHUDPanelForGamemode({
* gamemodes: [Gamemode.SURF],
* context: this,
* contextPanel: $.GetContextPanel()
* })
* }
Expand All @@ -88,12 +87,10 @@ export interface RegisterHUDPanelForGamemodeOptions {
* static {
* RegisterHUDPanelForGamemode({
* gamemodes: [Gamemode.BHOP],
* context: this,
* contextPanel: $.GetContextPanel(),
* onLoad: this.setup,
* handledEvents: [{
* events: [{
* event: 'HudProcessInput',
* callback: this.onUpdate,
* contextPanel: $.GetContextPanel()
* }]
* })
Expand All @@ -111,24 +108,22 @@ export interface RegisterHUDPanelForGamemodeOptions {
* @returns Cleanup function that unregisters all event handlers
*/
export function RegisterHUDPanelForGamemode({
context,
contextPanel,
onLoad,
gamemodes,
handledEvents,
unhandledEvents
events
}: RegisterHUDPanelForGamemodeOptions): () => void {
const contextPanel = $.GetContextPanel();

if (!(gamemodes?.length > 0)) {
throw new Error('RegisterHUDPanelForGamemode: no gamemode provided');
}

let handles: Array<{ event: keyof GlobalEventNameMap; handle: number; contextPanel?: GenericPanel }> = [];
let handles: Array<{ event: keyof GlobalEventNameMap; handle: number; panel?: GenericPanel }> = [];

const unregister = () =>
handles.forEach(({ event, handle, contextPanel }) =>
contextPanel === undefined
? $.UnregisterForUnhandledEvent(event, handle)
: $.UnregisterEventHandler(event, contextPanel, handle)
handles.forEach(({ event, handle, panel }) =>
panel ? $.UnregisterForUnhandledEvent(event, handle) : $.UnregisterEventHandler(event, panel, handle)
);

const handle = $.RegisterForUnhandledEvent('LevelInitPostEntity', () => {
Expand All @@ -137,22 +132,22 @@ export function RegisterHUDPanelForGamemode({

if (gamemodes.includes(GameModeAPI.GetCurrentGameMode())) {
contextPanel.enabled = true;
onLoad?.call(context);
onLoad?.();

for (const { event, callback } of unhandledEvents ?? []) {
events?.forEach(({ event, callback }) => {
handles.push({
event,
handle: $.RegisterForUnhandledEvent(event, callback.bind(context))
handle: $.RegisterForUnhandledEvent(event, callback)
});
}
});

for (const { event, contextPanel, callback } of handledEvents ?? []) {
handledEvents?.forEach(({ event, panel, callback }) => {
handles.push({
event,
contextPanel,
handle: $.RegisterEventHandler(event, contextPanel, callback.bind(context))
panel,
handle: $.RegisterEventHandler(event, panel, callback)
});
}
});
} else {
contextPanel.enabled = false;
}
Expand Down

0 comments on commit b46c6b5

Please sign in to comment.