fork/replay-manager-for-slippi

git clone https://git.julia.blue/fork/replay-manager-for-slippi

Grant Warmanadd character & stage reporting for parrygg (#197)82b5e4d

2.5.0
39.7 KiB1175 linesraw
1import { MatchResult, SlotState } from '@parry-gg/client';
2import { Backup, Report, VideogameAssetOff } from '@mui/icons-material';
3import {
4  Avatar,
5  Box,
6  Button,
7  CircularProgress,
8  Dialog,
9  DialogActions,
10  DialogContent,
11  DialogContentText,
12  DialogTitle,
13  Divider,
14  IconButton,
15  Stack,
16  Tooltip,
17  Typography,
18} from '@mui/material';
19import { MouseEventHandler, useEffect, useState } from 'react';
20import styled from '@emotion/styled';
21import {
22  ChallongeMatchItem,
23  EnforcerSetting,
24  EnforceState,
25  EnforceStatus,
26  Id,
27  Mode,
28  ParryggGame,
29  ParryggGameParticipant,
30  Player,
31  Replay,
32  ReportSettings,
33  Set,
34  StartggGame,
35  StartggGameSelection,
36  StartggSet,
37  State,
38  Stream,
39} from '../common/types';
40import {
41  characterNames,
42  characterParryggSlugs,
43  characterStartggIds,
44  isValidCharacter,
45  parryggCharacterColors,
46  stageNames,
47  stageParryggSlugs,
48  stageStartggIds,
49  startggCharacterIds,
50  startggStageIds,
51} from '../common/constants';
52import LabeledCheckbox from './LabeledCheckbox';
53import getCharacterIcon from './getCharacterIcon';
54import { assertInteger, assertString } from '../common/asserts';
55
56const bgColor = 'rgba(34, 178, 76, 0.2)';
57
58function getCharacterIconInner(
59  characterId: number | undefined,
60  costumeIndex?: number,
61) {
62  if (characterId === undefined) {
63    return getCharacterIcon(31, 0);
64  }
65  if (costumeIndex === undefined) {
66    return getCharacterIcon(characterId, 0);
67  }
68  return getCharacterIcon(characterId, costumeIndex);
69}
70
71const EntrantSection = styled(Stack)`
72  align-items: center;
73  width: 50%;
74`;
75
76const EntrantText = styled(Stack)`
77  margin: 0 4px;
78  min-width: 0;
79`;
80
81const EntrantScore = styled(EntrantText)`
82  width: 16px;
83`;
84
85const Name = styled.div`
86  overflow-x: hidden;
87  text-overflow: ellipsis;
88  white-space: nowrap;
89`;
90
91function isValid(player: Player) {
92  return player.playerType === 0 || player.playerType === 1;
93}
94
95function setAndReplaysValid(selectedReplays: Replay[], set: Set, mode: Mode) {
96  if (selectedReplays.length === 0) {
97    return { valid: false, reason: 'No replays selected' };
98  }
99  if (mode === Mode.CHALLONGE && set.state === State.COMPLETED) {
100    return { valid: false, reason: 'Set already completed' };
101  }
102
103  let reason = '';
104  const valid = selectedReplays.every((replay, i) => {
105    if (set.id === 0) {
106      if (!reason) {
107        reason = 'No set selected';
108      }
109      return false;
110    }
111    if (Number.isInteger(set.id) && (set.id as number) < 0) {
112      if (!reason) {
113        reason = 'Tiebreaker sets cannot be reported';
114      }
115      return false;
116    }
117
118    const validPlayers = replay.players.filter(isValid);
119    if (
120      validPlayers.length !==
121      set.entrant1Participants.length + set.entrant2Participants.length
122    ) {
123      if (!reason) {
124        reason = `Game ${i + 1} has wrong number of players`;
125      }
126      return false;
127    }
128    if (!(validPlayers.find((player) => player.isWinner) || replay.timeout)) {
129      if (!reason) {
130        reason = `Game ${i + 1} does not have a winner`;
131      }
132      return false;
133    }
134    if (!validPlayers.every((player) => player.playerOverrides.entrantId)) {
135      if (!reason) {
136        reason = `Game ${i + 1} does not have all players assigned`;
137      }
138      return false;
139    }
140    return true;
141  });
142
143  return { valid, reason };
144}
145
146function getScoresAndWinnerId(selectedReplays: Replay[]) {
147  let gameCount = 0;
148  const gameWins = new Map<Id, number>();
149  let leaderId: Id = 0;
150  let leaderWins = 0;
151  selectedReplays.forEach((replay) => {
152    const gameWinnerId = replay.players
153      .filter(isValid)
154      .find((player) => player.isWinner)?.playerOverrides.entrantId;
155    if (!gameWinnerId) {
156      return;
157    }
158
159    const n = (gameWins.get(gameWinnerId) || 0) + 1;
160    if (n > leaderWins) {
161      leaderWins = n;
162      leaderId = gameWinnerId;
163    }
164    gameCount += 1;
165    gameWins.set(gameWinnerId, n);
166  });
167
168  return {
169    scores: gameWins,
170    winnerId: leaderWins / gameCount > 0.5 ? leaderId : 0,
171  };
172}
173
174function getDisplayNameFromPlayer(player?: Player) {
175  return player?.playerOverrides.displayName || player?.displayName;
176}
177
178function ReportButton({
179  disabled,
180  elevate,
181  onClick,
182}: {
183  disabled?: boolean;
184  elevate: boolean;
185  onClick?: MouseEventHandler<HTMLButtonElement>;
186}) {
187  return (
188    <Button
189      disabled={disabled}
190      endIcon={<Backup />}
191      onClick={onClick}
192      size="small"
193      variant="contained"
194      sx={{
195        zIndex: (theme) => (elevate ? theme.zIndex.drawer + 2 : undefined),
196      }}
197    >
198      Report
199    </Button>
200  );
201}
202ReportButton.defaultProps = {
203  disabled: false,
204  onClick: undefined,
205};
206
207export default function SetControls({
208  copyReplays,
209  deleteReplays,
210  reportChallongeSet,
211  reportStartggSet,
212  reportParryggSet,
213  reportOfflineModeSet,
214  setReportSettings,
215  resetGuide,
216  mode,
217  isCopying,
218  copyDisabled,
219  isDeleting,
220  dqId,
221  hasRemainingReplays,
222  reportSettings,
223  selectedReplays,
224  set,
225  elevate,
226  enforcerVersion,
227  enforcerSetting,
228  smuggleCostumeIndex,
229  wouldDeleteCopyDir,
230  replayLoadCount,
231  undoSubdir,
232}: {
233  copyReplays: (
234    updatedSetFields?: {
235      id: Id;
236      sggId: number | null;
237      completedAtMs: number;
238      stream: Stream | null;
239    },
240    violators?: {
241      checkNames: Map<string, boolean>;
242      displayName: string;
243      entrantId: Id;
244    }[],
245  ) => Promise<void>;
246  deleteReplays: () => Promise<void>;
247  reportChallongeSet: (
248    matchId: string,
249    items: ChallongeMatchItem[],
250  ) => Promise<Set>;
251  reportStartggSet: (
252    set: StartggSet,
253    originalSet: Set,
254  ) => Promise<Set | undefined>;
255  reportParryggSet: (
256    result: MatchResult.AsObject,
257    originalSet: Set,
258    games?: ParryggGame[],
259  ) => Promise<Set | undefined>;
260  reportOfflineModeSet: (set: StartggSet) => Promise<Set>;
261  setReportSettings: (newReportSettings: ReportSettings) => Promise<void>;
262  resetGuide: () => void;
263  mode: Mode;
264  isCopying: boolean;
265  copyDisabled: boolean;
266  isDeleting: boolean;
267  dqId: Id;
268  hasRemainingReplays: boolean;
269  reportSettings: ReportSettings;
270  selectedReplays: Replay[];
271  set: Set;
272  elevate: boolean;
273  enforcerVersion: string;
274  enforcerSetting: EnforcerSetting;
275  smuggleCostumeIndex: boolean;
276  wouldDeleteCopyDir: boolean;
277  replayLoadCount: number;
278  undoSubdir: string;
279}) {
280  const [open, setOpen] = useState(false);
281  const [reporting, setReporting] = useState(false);
282  const [reportError, setReportError] = useState('');
283  const [reportErrorOpen, setReportErrorOpen] = useState(false);
284  const [startggSet, setStartggSet] = useState<StartggSet>({
285    setId: set.id,
286    winnerId: 0,
287    isDQ: false,
288    gameData: [],
289  });
290  const [challongeMatchItems, setChallongeMatchItems] = useState<
291    ChallongeMatchItem[]
292  >([
293    {
294      participant_id: '',
295      score_set: '',
296      rank: 0,
297      advancing: false,
298    },
299    {
300      participant_id: '',
301      score_set: '',
302      rank: 0,
303      advancing: false,
304    },
305  ]);
306  const [parryggMatchResult, setParryggMatchResult] =
307    useState<MatchResult.AsObject>({
308      slotsList: [
309        {
310          slot: 0,
311          score: 0,
312          state: SlotState.SLOT_STATE_NUMERIC,
313        },
314        {
315          slot: 1,
316          score: 0,
317          state: SlotState.SLOT_STATE_NUMERIC,
318        },
319      ],
320    });
321
322  const [enforcerResultOpen, setEnforcerResultOpen] = useState(false);
323  const [enforceState, setEnforceState] = useState<EnforceState>({
324    status: EnforceStatus.DONE,
325    fileNameToPlayerFailures: new Map(),
326  });
327  useEffect(() => {
328    window.electron.onEnforceState(
329      (event, newEnforceState, newReplayLoadCount) => {
330        if (newReplayLoadCount >= replayLoadCount) {
331          setEnforceState(newEnforceState);
332        }
333      },
334    );
335  }, [replayLoadCount]);
336  const selectedReplaysWithEnforceErrors =
337    enforceState.status === EnforceStatus.DONE
338      ? selectedReplays.filter((replay) =>
339          enforceState.fileNameToPlayerFailures.has(replay.fileName),
340        )
341      : [];
342  let showEnforcerPopup = false;
343  if (enforcerSetting === EnforcerSetting.POP_UP_ALL) {
344    showEnforcerPopup = selectedReplaysWithEnforceErrors.length > 0;
345  } else if (enforcerSetting === EnforcerSetting.POP_UP_GOOMWAVE) {
346    showEnforcerPopup = selectedReplaysWithEnforceErrors.some((replay) =>
347      enforceState.fileNameToPlayerFailures
348        .get(replay.fileName)!
349        .some((enforcerPlayerError) =>
350          enforcerPlayerError.checkNames.includes('GoomWave Clamping'),
351        ),
352    );
353  }
354
355  const isDq = dqId === set.entrant1Id || dqId === set.entrant2Id;
356  const validSelections = setAndReplaysValid(selectedReplays, set, mode);
357  let scores = new Map<Id, number>();
358  let winnerId: Id = 0;
359  if (validSelections.valid) {
360    ({ scores, winnerId } = getScoresAndWinnerId(selectedReplays));
361  } else if (isDq) {
362    if (dqId === set.entrant1Id) {
363      scores.set(set.entrant1Id, -1);
364      scores.set(set.entrant2Id, 0);
365      winnerId = set.entrant2Id;
366    } else {
367      scores.set(set.entrant1Id, 0);
368      scores.set(set.entrant2Id, -1);
369      winnerId = set.entrant1Id;
370    }
371  }
372
373  const entrant1SetScore = scores.get(set.entrant1Id) || 0;
374  const entrant2SetScore = scores.get(set.entrant2Id) || 0;
375
376  const getStartggSet = (): StartggSet => {
377    if (isDq) {
378      return { setId: set.id, winnerId, isDQ: true, gameData: [] };
379    }
380
381    const gameData: StartggGame[] = [];
382    selectedReplays.forEach((replay, i) => {
383      const gameWinnerId = replay.players.find((player) => player.isWinner)
384        ?.playerOverrides.entrantId;
385      if (!gameWinnerId) {
386        return;
387      }
388
389      const originalEntrant1Score = set.gameScores[i]?.entrant1Score ?? 0;
390      const originalEntrant2Score = set.gameScores[i]?.entrant2Score ?? 0;
391      let entrant1CostumeOffset = Math.floor(originalEntrant1Score / 100) * 100;
392      let entrant2CostumeOffset = Math.floor(originalEntrant2Score / 100) * 100;
393      let entrant1Stocks = originalEntrant1Score % 100;
394      let entrant2Stocks = originalEntrant2Score % 100;
395      const participantIdToSelection = new Map<Id, StartggGameSelection>();
396      const validPlayers = replay.players.filter(
397        (player) =>
398          isValid(player) && isValidCharacter(player.externalCharacterId),
399      );
400      validPlayers.forEach((player) => {
401        const { entrantId, participantId } = player.playerOverrides;
402        participantIdToSelection.set(participantId, {
403          characterId: characterStartggIds.get(player.externalCharacterId)!,
404          entrantId,
405        });
406        if (validPlayers.length === 2) {
407          if (entrantId === set.entrant1Id) {
408            if (smuggleCostumeIndex) {
409              entrant1CostumeOffset = (player.costumeIndex + 1) * 100;
410            }
411            if (player.stocksRemaining >= 0) {
412              entrant1Stocks = player.stocksRemaining;
413            }
414          } else {
415            if (smuggleCostumeIndex) {
416              entrant2CostumeOffset = (player.costumeIndex + 1) * 100;
417            }
418            if (player.stocksRemaining >= 0) {
419              entrant2Stocks = player.stocksRemaining;
420            }
421          }
422        }
423      });
424      const selections = [
425        ...set.entrant1Participants.map(
426          (participant) => participantIdToSelection.get(participant.id)!,
427        ),
428        ...set.entrant2Participants.map(
429          (participant) => participantIdToSelection.get(participant.id)!,
430        ),
431      ];
432      gameData.push({
433        entrant1Score: entrant1CostumeOffset + entrant1Stocks,
434        entrant2Score: entrant2CostumeOffset + entrant2Stocks,
435        gameNum: i + 1,
436        stageId: stageStartggIds.get(replay.stageId),
437        selections,
438        winnerId: assertInteger(gameWinnerId),
439      });
440    });
441    return { setId: set.id, winnerId, isDQ: false, gameData };
442  };
443
444  // Per-game character/color/stage data for parry.gg, mirroring getStartggSet.
445  const getParryggGames = (): ParryggGame[] => {
446    const games: ParryggGame[] = [];
447    selectedReplays.forEach((replay, i) => {
448      const gameWinnerId = replay.players.find((player) => player.isWinner)
449        ?.playerOverrides.entrantId;
450      if (!gameWinnerId) {
451        return;
452      }
453
454      // slot 0 = entrant1, slot 1 = entrant2 (matches getMatchResult).
455      const slotParticipants: [
456        ParryggGameParticipant[],
457        ParryggGameParticipant[],
458      ] = [[], []];
459      replay.players
460        .filter(
461          (player) =>
462            isValid(player) && isValidCharacter(player.externalCharacterId),
463        )
464        .forEach((player) => {
465          const { entrantId, participantId } = player.playerOverrides;
466          const slotIndex = entrantId === set.entrant1Id ? 0 : 1;
467          slotParticipants[slotIndex].push({
468            userId: participantId.toString(),
469            characters: [
470              {
471                characterSlug: characterParryggSlugs.get(
472                  player.externalCharacterId,
473                )!,
474                color:
475                  parryggCharacterColors.get(player.externalCharacterId)?.[
476                    player.costumeIndex
477                  ] ?? null,
478              },
479            ],
480          });
481        });
482
483      const winnerSlotIndex = gameWinnerId === set.entrant1Id ? 0 : 1;
484      games.push({
485        index: i,
486        stageSlug: stageParryggSlugs.get(replay.stageId),
487        slots: [0, 1].map((slot) => ({
488          slot,
489          score: slot === winnerSlotIndex ? 1 : 0,
490          participants: slotParticipants[slot],
491        })),
492      });
493    });
494    return games;
495  };
496
497  const getChallongeMatchItems = (): ChallongeMatchItem[] => [
498    {
499      participant_id: set.entrant1Id.toString(10),
500      score_set: entrant1SetScore.toString(10),
501      rank: winnerId === set.entrant1Id ? 1 : 2,
502      advancing: winnerId === set.entrant1Id,
503    },
504    {
505      participant_id: set.entrant2Id.toString(10),
506      score_set: entrant2SetScore.toString(10),
507      rank: winnerId === set.entrant2Id ? 1 : 2,
508      advancing: winnerId === set.entrant2Id,
509    },
510  ];
511
512  const getMatchResult = (): MatchResult.AsObject => {
513    const entrant1Dq = isDq && dqId === set.entrant1Id;
514    const entrant2Dq = isDq && dqId === set.entrant2Id;
515
516    return {
517      slotsList: [
518        {
519          slot: 0,
520          score: entrant1Dq ? 0 : entrant1SetScore,
521          state: entrant1Dq
522            ? SlotState.SLOT_STATE_DQ
523            : SlotState.SLOT_STATE_NUMERIC,
524        },
525        {
526          slot: 1,
527          score: entrant2Dq ? 0 : entrant2SetScore,
528          state: entrant2Dq
529            ? SlotState.SLOT_STATE_DQ
530            : SlotState.SLOT_STATE_NUMERIC,
531        },
532      ],
533    };
534  };
535
536  let deleteOverrideReason = '';
537  if (set.fullRoundText === 'Grand Final' && hasRemainingReplays) {
538    deleteOverrideReason = 'possible Grand Finals Reset replays detected';
539  } else if (wouldDeleteCopyDir) {
540    deleteOverrideReason = 'would delete replays in copy folder';
541  }
542
543  let reportCopyDeleteIntent = 'Report';
544  if (reportSettings.alsoCopy || undoSubdir) {
545    reportCopyDeleteIntent += ', Copy';
546  }
547  if (
548    (reportSettings.alsoCopy &&
549      reportSettings.alsoDelete &&
550      deleteOverrideReason.length === 0) ||
551    undoSubdir
552  ) {
553    reportCopyDeleteIntent += ', Delete';
554  }
555
556  let reportCopyDeleteButton = reportCopyDeleteIntent;
557  if (enforceState.status === EnforceStatus.PENDING) {
558    reportCopyDeleteButton = 'Checking with SLP Enforcer';
559  } else if ((reportSettings.alsoCopy || undoSubdir) && copyDisabled) {
560    reportCopyDeleteButton = 'Copy destination not set';
561  } else if ((reportSettings.alsoCopy || undoSubdir) && isCopying) {
562    reportCopyDeleteButton = 'Copying';
563  } else if ((reportSettings.alsoDelete || undoSubdir) && isDeleting) {
564    reportCopyDeleteButton = 'Deleting';
565  } else if (reporting) {
566    reportCopyDeleteButton = 'Reporting';
567  }
568
569  return (
570    <>
571      {validSelections.valid && (winnerId || isDq) ? (
572        <ReportButton
573          elevate={elevate}
574          onClick={() => {
575            if (mode === Mode.STARTGG || mode === Mode.OFFLINE_MODE) {
576              setStartggSet(getStartggSet());
577            } else if (mode === Mode.CHALLONGE) {
578              setChallongeMatchItems(getChallongeMatchItems());
579            } else if (mode === Mode.PARRYGG) {
580              setParryggMatchResult(getMatchResult());
581            }
582            if (
583              (selectedReplaysWithEnforceErrors.length > 0 &&
584                showEnforcerPopup) ||
585              enforceState.status === EnforceStatus.ERROR
586            ) {
587              setEnforcerResultOpen(true);
588            }
589            setOpen(true);
590          }}
591        />
592      ) : (
593        <Tooltip
594          arrow
595          title={!validSelections.valid ? validSelections.reason : 'No winner'}
596        >
597          <div>
598            <ReportButton disabled elevate={elevate} />
599          </div>
600        </Tooltip>
601      )}
602      <Dialog
603        open={open}
604        onClose={() => {
605          setOpen(false);
606          setStartggSet({
607            setId: set.id,
608            winnerId: 0,
609            isDQ: false,
610            gameData: [],
611          });
612        }}
613      >
614        <DialogTitle typography="body1">
615          Report set on {mode === Mode.STARTGG && 'start.gg'}
616          {mode === Mode.CHALLONGE && 'Challonge'}
617          {mode === Mode.PARRYGG && 'parry.gg'}
618          {mode === Mode.OFFLINE_MODE && 'Offline Mode'}
619        </DialogTitle>
620        <DialogContent sx={{ width: '500px' }}>
621          <Stack>
622            <Box sx={{ typography: 'caption' }} textAlign="center">
623              {set.fullRoundText}
624            </Box>
625            <Stack
626              alignItems="center"
627              direction="row"
628              sx={{ typography: 'h5' }}
629            >
630              <EntrantSection
631                borderRight={1}
632                direction="row-reverse"
633                style={{
634                  backgroundColor:
635                    set.entrant1Id === winnerId ? bgColor : undefined,
636                }}
637              >
638                <Box marginRight="8px" width="24px" textAlign="right">
639                  {entrant1SetScore}
640                </Box>
641                <Stack textAlign="right">
642                  <Name>{set.entrant1Participants[0].displayName}</Name>
643                  {set.entrant1Participants.length > 1 && (
644                    <Name>{set.entrant1Participants[1].displayName}</Name>
645                  )}
646                </Stack>
647              </EntrantSection>
648              <EntrantSection
649                borderLeft={1}
650                direction="row"
651                style={{
652                  backgroundColor:
653                    set.entrant2Id === winnerId ? bgColor : undefined,
654                }}
655              >
656                <Box marginLeft="8px" width="24px">
657                  {entrant2SetScore}
658                </Box>
659                <Stack>
660                  <Name>{set.entrant2Participants[0].displayName}</Name>
661                  {set.entrant2Participants.length > 1 && (
662                    <Name>{set.entrant2Participants[1].displayName}</Name>
663                  )}
664                </Stack>
665              </EntrantSection>
666            </Stack>
667          </Stack>
668          <Divider sx={{ marginTop: '16px' }} />
669          <Stack flexGrow={1}>
670            {(mode === Mode.STARTGG || mode === Mode.OFFLINE_MODE) &&
671              startggSet.gameData.map((gameData) => (
672                <Stack key={gameData.gameNum} marginTop="8px">
673                  {gameData.stageId && (
674                    <Box sx={{ typography: 'caption' }} textAlign="center">
675                      {stageNames.get(startggStageIds.get(gameData.stageId)!)}
676                    </Box>
677                  )}
678                  <Stack direction="row" sx={{ typography: 'body2' }}>
679                    <EntrantSection borderRight={1} direction="row-reverse">
680                      <Stack
681                        alignItems="center"
682                        direction="row-reverse"
683                        paddingTop="4px"
684                        paddingBottom="4px"
685                        paddingLeft={
686                          set.entrant1Participants.length === 1
687                            ? '4px'
688                            : undefined
689                        }
690                        style={{
691                          backgroundColor:
692                            set.entrant1Id === gameData.winnerId
693                              ? bgColor
694                              : undefined,
695                        }}
696                      >
697                        <EntrantScore textAlign="right">
698                          {set.entrant1Id === gameData.winnerId && 'W'}
699                        </EntrantScore>
700                        {set.entrant1Participants.length === 1 && (
701                          <Avatar
702                            alt={characterNames.get(
703                              startggCharacterIds.get(
704                                gameData.selections[0].characterId,
705                              )!,
706                            )}
707                            src={getCharacterIconInner(
708                              startggCharacterIds.get(
709                                gameData.selections[0].characterId,
710                              ),
711                              gameData.entrant1Score >= 100
712                                ? Math.floor(gameData.entrant1Score / 100) - 1
713                                : undefined,
714                            )}
715                            sx={{ height: 24, width: 24 }}
716                            variant="square"
717                          />
718                        )}
719                        {set.entrant1Participants.length === 2 && (
720                          <>
721                            <Avatar
722                              alt={characterNames.get(
723                                startggCharacterIds.get(
724                                  gameData.selections[1].characterId,
725                                )!,
726                              )}
727                              src={getCharacterIconInner(
728                                startggCharacterIds.get(
729                                  gameData.selections[1].characterId,
730                                ),
731                              )}
732                              sx={{ height: 24, width: 24 }}
733                              variant="square"
734                            />
735                            <Avatar
736                              alt={characterNames.get(
737                                startggCharacterIds.get(
738                                  gameData.selections[0].characterId,
739                                )!,
740                              )}
741                              src={getCharacterIconInner(
742                                startggCharacterIds.get(
743                                  gameData.selections[0].characterId,
744                                ),
745                              )}
746                              sx={{ height: 24, width: 24 }}
747                              variant="square"
748                            />
749                          </>
750                        )}
751                      </Stack>
752                      {set.entrant1Participants.length === 1 &&
753                        set.entrant1Id === gameData.winnerId &&
754                        gameData.entrant1Score % 100 && (
755                          <Tooltip
756                            arrow
757                            placement="left"
758                            title={`${gameData.entrant1Score % 100} stock`}
759                          >
760                            <Stack
761                              alignItems="end"
762                              direction="row"
763                              gap="1px"
764                              marginRight="8px"
765                              height="100%"
766                            >
767                              {[
768                                ...Array(gameData.entrant1Score % 100).keys(),
769                              ].map(() => (
770                                <Avatar
771                                  src={getCharacterIconInner(
772                                    startggCharacterIds.get(
773                                      gameData.selections[0].characterId,
774                                    ),
775                                    gameData.entrant1Score >= 100
776                                      ? Math.floor(
777                                          gameData.entrant1Score / 100,
778                                        ) - 1
779                                      : undefined,
780                                  )}
781                                  sx={{ height: 12, width: 12 }}
782                                  variant="square"
783                                />
784                              ))}
785                            </Stack>
786                          </Tooltip>
787                        )}
788                    </EntrantSection>
789                    <EntrantSection borderLeft={1} direction="row">
790                      <Stack
791                        alignItems="center"
792                        direction="row"
793                        paddingTop="4px"
794                        paddingBottom="4px"
795                        paddingRight={
796                          set.entrant2Participants.length === 1
797                            ? '4px'
798                            : undefined
799                        }
800                        style={{
801                          backgroundColor:
802                            set.entrant2Id === gameData.winnerId
803                              ? bgColor
804                              : undefined,
805                        }}
806                      >
807                        <EntrantScore>
808                          {set.entrant2Id === gameData.winnerId && 'W'}
809                        </EntrantScore>
810                        {set.entrant2Participants.length === 1 && (
811                          <Avatar
812                            alt={characterNames.get(
813                              startggCharacterIds.get(
814                                gameData.selections[1].characterId,
815                              )!,
816                            )}
817                            src={getCharacterIconInner(
818                              startggCharacterIds.get(
819                                gameData.selections[1].characterId,
820                              ),
821                              gameData.entrant2Score >= 100
822                                ? Math.floor(gameData.entrant2Score / 100) - 1
823                                : undefined,
824                            )}
825                            sx={{ height: 24, width: 24 }}
826                            variant="square"
827                          />
828                        )}
829                        {set.entrant2Participants.length === 2 && (
830                          <>
831                            <Avatar
832                              alt={characterNames.get(
833                                startggCharacterIds.get(
834                                  gameData.selections[
835                                    set.entrant1Participants.length
836                                  ].characterId,
837                                )!,
838                              )}
839                              src={getCharacterIconInner(
840                                startggCharacterIds.get(
841                                  gameData.selections[
842                                    set.entrant1Participants.length
843                                  ].characterId,
844                                ),
845                              )}
846                              sx={{ height: 24, width: 24 }}
847                              variant="square"
848                            />
849                            <Avatar
850                              alt={characterNames.get(
851                                startggCharacterIds.get(
852                                  gameData.selections[
853                                    set.entrant1Participants.length + 1
854                                  ].characterId,
855                                )!,
856                              )}
857                              src={getCharacterIconInner(
858                                startggCharacterIds.get(
859                                  gameData.selections[
860                                    set.entrant1Participants.length + 1
861                                  ].characterId,
862                                ),
863                              )}
864                              sx={{ height: 24, width: 24 }}
865                              variant="square"
866                            />
867                          </>
868                        )}
869                      </Stack>
870                      {set.entrant2Participants.length === 1 &&
871                        set.entrant2Id === gameData.winnerId &&
872                        gameData.entrant2Score % 100 && (
873                          <Tooltip
874                            arrow
875                            placement="right"
876                            title={`${gameData.entrant2Score % 100} stock`}
877                          >
878                            <Stack
879                              alignItems="end"
880                              direction="row"
881                              gap="1px"
882                              marginLeft="8px"
883                              height="100%"
884                            >
885                              {[
886                                ...Array(gameData.entrant2Score % 100).keys(),
887                              ].map(() => (
888                                <Avatar
889                                  src={getCharacterIconInner(
890                                    startggCharacterIds.get(
891                                      gameData.selections[1].characterId,
892                                    ),
893                                    gameData.entrant2Score >= 100
894                                      ? Math.floor(
895                                          gameData.entrant2Score / 100,
896                                        ) - 1
897                                      : undefined,
898                                  )}
899                                  sx={{ height: 12, width: 12 }}
900                                  variant="square"
901                                />
902                              ))}
903                            </Stack>
904                          </Tooltip>
905                        )}
906                    </EntrantSection>
907                  </Stack>
908                </Stack>
909              ))}
910          </Stack>
911          <Divider sx={{ marginTop: '8px' }} />
912          <Stack justifyContent="flex-end">
913            <LabeledCheckbox
914              checked={reportSettings.alsoCopy || undoSubdir.length > 0}
915              disabled={undoSubdir.length > 0}
916              label="Copy replays after reporting"
917              labelPlacement="start"
918              set={(checked: boolean) => {
919                const newReportSettings = { ...reportSettings };
920                newReportSettings.alsoCopy = checked;
921                setReportSettings(newReportSettings);
922              }}
923            />
924            <LabeledCheckbox
925              checked={reportSettings.alsoDelete || undoSubdir.length > 0}
926              disabled={
927                !reportSettings.alsoCopy ||
928                deleteOverrideReason.length > 0 ||
929                undoSubdir.length > 0
930              }
931              label={
932                deleteOverrideReason.length > 0
933                  ? `Delete disabled, ${deleteOverrideReason}`
934                  : '...then delete originals and eject'
935              }
936              labelPlacement="start"
937              set={(checked: boolean) => {
938                const newReportSettings = { ...reportSettings };
939                newReportSettings.alsoDelete = checked;
940                setReportSettings(newReportSettings);
941              }}
942            />
943          </Stack>
944        </DialogContent>
945        <DialogActions>
946          {enforceState.status === EnforceStatus.ERROR && (
947            <Tooltip arrow placement="top" title="SLP Enforcer Failure">
948              <IconButton
949                onClick={() => {
950                  setEnforcerResultOpen(true);
951                }}
952              >
953                <Report />
954              </IconButton>
955            </Tooltip>
956          )}
957          {selectedReplaysWithEnforceErrors.length > 0 && (
958            <Tooltip
959              arrow
960              placement="top"
961              title="Controller Ruleset Violation Detected"
962            >
963              <IconButton
964                onClick={() => {
965                  setEnforcerResultOpen(true);
966                }}
967              >
968                <VideogameAssetOff />
969              </IconButton>
970            </Tooltip>
971          )}
972          <Button
973            disabled={
974              reporting ||
975              (reportSettings.alsoCopy && isCopying) ||
976              (reportSettings.alsoCopy && copyDisabled) ||
977              enforceState.status === EnforceStatus.PENDING
978            }
979            endIcon={
980              reporting || enforceState.status === EnforceStatus.PENDING ? (
981                <CircularProgress size="24px" />
982              ) : (
983                <Backup />
984              )
985            }
986            onClick={async () => {
987              setReporting(true);
988              try {
989                let updatedSet: Set | undefined;
990                if (mode === Mode.STARTGG) {
991                  updatedSet = await reportStartggSet(startggSet, set);
992                } else if (mode === Mode.CHALLONGE) {
993                  updatedSet = await reportChallongeSet(
994                    assertString(set.id),
995                    challongeMatchItems,
996                  );
997                } else if (mode === Mode.PARRYGG) {
998                  updatedSet = await reportParryggSet(
999                    parryggMatchResult,
1000                    set,
1001                    isDq ? undefined : getParryggGames(),
1002                  );
1003                } else if (mode === Mode.OFFLINE_MODE) {
1004                  updatedSet = await reportOfflineModeSet(startggSet);
1005                }
1006                if (reportSettings.alsoCopy || undoSubdir) {
1007                  const entrantIdToDisplayNameAndCheckNames = new Map<
1008                    Id,
1009                    { checkNames: Map<string, boolean>; displayName: string }
1010                  >();
1011                  selectedReplaysWithEnforceErrors.forEach((replay) => {
1012                    enforceState.fileNameToPlayerFailures
1013                      .get(replay.fileName)!
1014                      .forEach((playerFailure) => {
1015                        const failurePlayer = replay.players.find(
1016                          (player) => player.port === playerFailure.port,
1017                        )!;
1018                        const displayName =
1019                          failurePlayer.playerOverrides.displayName ||
1020                          failurePlayer.displayName;
1021                        const { entrantId } = failurePlayer.playerOverrides;
1022                        if (entrantId) {
1023                          if (
1024                            entrantIdToDisplayNameAndCheckNames.has(entrantId)
1025                          ) {
1026                            const { checkNames } =
1027                              entrantIdToDisplayNameAndCheckNames.get(
1028                                entrantId,
1029                              )!;
1030                            playerFailure.checkNames.forEach((checkName) => {
1031                              checkNames.set(checkName, true);
1032                            });
1033                          } else {
1034                            entrantIdToDisplayNameAndCheckNames.set(entrantId, {
1035                              checkNames: new Map(
1036                                playerFailure.checkNames.map((checkName) => [
1037                                  checkName,
1038                                  true,
1039                                ]),
1040                              ),
1041                              displayName,
1042                            });
1043                          }
1044                        }
1045                      });
1046                  });
1047                  await copyReplays(
1048                    updatedSet
1049                      ? {
1050                          id: updatedSet.id,
1051                          sggId: updatedSet.sggId,
1052                          completedAtMs: updatedSet.completedAtMs,
1053                          stream: updatedSet.stream,
1054                        }
1055                      : undefined,
1056                    Array.from(entrantIdToDisplayNameAndCheckNames).map(
1057                      ([entrantId, { checkNames, displayName }]) => ({
1058                        checkNames,
1059                        displayName,
1060                        entrantId,
1061                      }),
1062                    ),
1063                  );
1064                }
1065                if (
1066                  (reportSettings.alsoCopy &&
1067                    reportSettings.alsoDelete &&
1068                    deleteOverrideReason.length === 0) ||
1069                  undoSubdir
1070                ) {
1071                  await deleteReplays();
1072                }
1073                setOpen(false);
1074                setStartggSet({
1075                  setId: set.id,
1076                  winnerId: 0,
1077                  isDQ: false,
1078                  gameData: [],
1079                });
1080                resetGuide();
1081              } catch (e: any) {
1082                const message = e instanceof Error ? e.message : e;
1083                setReportError(message);
1084                setReportErrorOpen(true);
1085              } finally {
1086                setReporting(false);
1087              }
1088            }}
1089            variant="contained"
1090          >
1091            {reportCopyDeleteButton}
1092          </Button>
1093        </DialogActions>
1094      </Dialog>
1095      <Dialog
1096        open={reportErrorOpen}
1097        onClose={() => {
1098          setReportErrorOpen(false);
1099          setReportError('');
1100        }}
1101      >
1102        <DialogTitle>{reportCopyDeleteIntent} error!</DialogTitle>
1103        <DialogContent>
1104          <DialogContentText>{reportError}</DialogContentText>
1105        </DialogContent>
1106        <DialogActions>
1107          <Button
1108            onClick={() => {
1109              setReportErrorOpen(false);
1110              setReportError('');
1111            }}
1112          >
1113            Close
1114          </Button>
1115        </DialogActions>
1116      </Dialog>
1117      <Dialog
1118        open={enforcerResultOpen}
1119        onClose={() => {
1120          setEnforcerResultOpen(false);
1121        }}
1122      >
1123        <Stack
1124          alignItems="center"
1125          direction="row"
1126          justifyContent="space-between"
1127          marginRight="24px"
1128        >
1129          <DialogTitle>
1130            {enforceState.status === EnforceStatus.DONE &&
1131              'Controller Ruleset Violation Detected'}
1132            {enforceState.status === EnforceStatus.ERROR &&
1133              'SLP Enforcer Failure'}
1134          </DialogTitle>
1135          <Typography variant="caption">
1136            SLP Enforcer version {enforcerVersion}
1137          </Typography>
1138        </Stack>
1139        <DialogContent sx={{ width: '500px' }}>
1140          {enforceState.status === EnforceStatus.DONE && (
1141            <Stack spacing="8px">
1142              {selectedReplaysWithEnforceErrors.map((selectedReplay) => (
1143                <Box key={selectedReplay.fileName}>
1144                  <Box typography="caption">
1145                    {stageNames.get(selectedReplay.stageId)}
1146                  </Box>
1147                  {enforceState.fileNameToPlayerFailures
1148                    .get(selectedReplay.fileName)!
1149                    .map((enforcePlayerFailure) => (
1150                      <Box key={enforcePlayerFailure.port} typography="body2">
1151                        {getDisplayNameFromPlayer(
1152                          selectedReplay.players.find(
1153                            (player) =>
1154                              player.port === enforcePlayerFailure.port,
1155                          ),
1156                        )}
1157                        : {enforcePlayerFailure.checkNames.join(', ')}
1158                      </Box>
1159                    ))}
1160                </Box>
1161              ))}
1162            </Stack>
1163          )}
1164          {enforceState.status === EnforceStatus.ERROR && (
1165            <DialogContentText>
1166              {enforceState.reason instanceof Error
1167                ? enforceState.reason.message
1168                : enforceState.reason.toString()}
1169            </DialogContentText>
1170          )}
1171        </DialogContent>
1172      </Dialog>
1173    </>
1174  );
1175}