forked from Pathoschild/StardewMods
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathModEntry.cs
More file actions
334 lines (285 loc) · 12.8 KB
/
ModEntry.cs
File metadata and controls
334 lines (285 loc) · 12.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Pathoschild.Stardew.Common;
using Pathoschild.Stardew.Common.Integrations.BetterGameMenu;
using Pathoschild.Stardew.Common.Integrations.GenericModConfigMenu;
using Pathoschild.Stardew.Common.Integrations.IconicFramework;
using Pathoschild.Stardew.DebugMode.Framework;
using StardewModdingAPI;
using StardewModdingAPI.Events;
using StardewModdingAPI.Utilities;
using StardewValley;
using StardewValley.Menus;
using StardewValley.Minigames;
using StardewValley.Mods;
namespace Pathoschild.Stardew.DebugMode;
/// <summary>The mod entry point.</summary>
internal class ModEntry : Mod
{
/*********
** Fields
*********/
/// <summary>The mod configuration settings.</summary>
private ModConfig Config = null!; // set in Entry
/// <summary>The configured key bindings.</summary>
private ModConfigKeys Keys => this.Config.Controls;
/// <summary>Whether to show the debug info overlay.</summary>
private readonly PerScreen<bool> ShowOverlay = new();
/// <summary>The Better Game Menu integration.</summary>
private BetterGameMenuIntegration? BetterGameMenu;
/// <summary>Whether the built-in debug mode is enabled.</summary>
private bool GameDebugMode
{
get => Game1.debugMode;
set
{
Game1.debugMode = value;
Program.releaseBuild = !value;
}
}
/// <summary>A pixel texture that can be stretched and colorized for display.</summary>
private readonly Lazy<Texture2D> Pixel = new(ModEntry.CreatePixel);
/// <summary>Keyboard keys which are mapped to a destructive action in debug mode. See <see cref="ModConfig.AllowDangerousCommands"/>.</summary>
private readonly SButton[] DestructiveKeys = [
SButton.P, // ends current day
SButton.M, // ends current season
SButton.H, // randomizes player's hat
SButton.I, // randomizes player's hair
SButton.J, // randomizes player's shirt and pants
SButton.L, // randomizes player
SButton.U, // randomizes farmhouse wallpaper and floors
SButton.F10 // tries to launch a multiplayer server and crashes
];
/*********
** Public methods
*********/
/// <inheritdoc />
public override void Entry(IModHelper helper)
{
CommonHelper.RemoveObsoleteFiles(this, "DebugMode.pdb"); // removed in 1.13.9
// init
I18n.Init(helper.Translation);
this.Config = helper.ReadConfig<ModConfig>();
this.Config.AllowDangerousCommands = this.Config is { AllowGameDebug: true, AllowDangerousCommands: true }; // normalize for convenience
// hook events
helper.Events.GameLoop.GameLaunched += this.OnGameLaunched;
helper.Events.Input.ButtonsChanged += this.OnButtonsChanged;
helper.Events.Display.RenderedStep += this.OnRenderedStep;
helper.Events.Player.Warped += this.OnWarped;
// validate translations
if (!helper.Translation.GetTranslations().Any())
this.Monitor.Log("The translation files in this mod's i18n folder seem to be missing. The mod will still work, but you'll see 'missing translation' messages. Try reinstalling the mod to fix this.", LogLevel.Warn);
}
/*********
** Private methods
*********/
/****
** Event handlers
****/
/// <inheritdoc cref="IGameLoopEvents.GameLaunched" />
private void OnGameLaunched(object? sender, GameLaunchedEventArgs e)
{
// add config UI
this.AddGenericModConfigMenu(
new GenericModConfigMenuIntegrationForDebugMode(),
get: () => this.Config,
set: config => this.Config = config
);
// add Better Game Menu support
this.BetterGameMenu = new(this.Helper.ModRegistry, this.Monitor);
// add Iconic Framework icon
IconicFrameworkIntegration iconicFramework = new(this.Helper.ModRegistry, this.Monitor);
if (iconicFramework.IsLoaded)
{
iconicFramework.AddToolbarIcon(
this.Helper.ModContent.GetInternalAssetName("assets/icon.png").BaseName,
new Rectangle(0, 0, 16, 16),
I18n.Icon_ToggleDebugMode_Name,
I18n.Icon_ToggleDebugMode_Desc,
this.ToggleDebugMenu
);
}
}
/// <inheritdoc cref="IInputEvents.ButtonsChanged" />
private void OnButtonsChanged(object? sender, ButtonsChangedEventArgs e)
{
// toggle debug menu
if (this.Keys.ToggleDebug.JustPressed())
{
this.ToggleDebugMenu();
}
// suppress dangerous actions
if (this.GameDebugMode && !this.Config.AllowDangerousCommands)
{
foreach (SButton button in e.Pressed)
{
if (this.DestructiveKeys.Contains(button))
this.Helper.Input.Suppress(button);
}
}
}
/// <inheritdoc cref="IPlayerEvents.Warped" />
private void OnWarped(object? sender, WarpedEventArgs e)
{
if (this.GameDebugMode && e.IsLocalPlayer)
this.CorrectEntryPosition(e.NewLocation, Game1.player);
}
/// <inheritdoc cref="IDisplayEvents.Rendered" />
public void OnRenderedStep(object? sender, RenderedStepEventArgs e)
{
if (this.ShowOverlay.Value && e.Step is RenderSteps.Overlays)
this.DrawOverlay(Game1.spriteBatch, Game1.smallFont, this.Pixel.Value);
}
/****
** Methods
****/
/// <summary>Toggle the debug menu.</summary>
private void ToggleDebugMenu()
{
this.ShowOverlay.Value = !this.ShowOverlay.Value;
if (this.Config.AllowGameDebug)
this.GameDebugMode = !this.GameDebugMode;
}
/// <summary>Correct the player's position when they warp into an area.</summary>
/// <param name="location">The location the player entered.</param>
/// <param name="player">The player who just warped.</param>
private void CorrectEntryPosition(GameLocation location, Farmer player)
{
switch (location.Name)
{
// desert (move from inside wall to natural entry point)
case "SandyHouse":
this.MovePlayerFrom(player, new Vector2(16, 3), new Vector2(4, 9), PlayerDirection.Up);
break;
// mountain (move down a bit to natural entry point)
case "Mountain":
this.MovePlayerFrom(player, new Vector2(15, 35), new Vector2(15, 40), PlayerDirection.Up);
break;
// town (move from middle of field near community center to path between town and community center)
case "Town":
this.MovePlayerFrom(player, new Vector2(35, 35), new Vector2(48, 43), PlayerDirection.Up);
break;
}
}
/// <summary>Move the player from one tile to another, if they're on that tile.</summary>
/// <param name="player">The player to move.</param>
/// <param name="fromTile">The tile position from which to move the player.</param>
/// <param name="toTile">The tile position to which to move the player.</param>
/// <param name="facingDirection">The direction the player should be facing after they're moved.</param>
private void MovePlayerFrom(Farmer player, Vector2 fromTile, Vector2 toTile, PlayerDirection facingDirection)
{
Point playerTile = player.TilePoint;
if (playerTile.X == (int)fromTile.X && playerTile.Y == (int)fromTile.Y)
{
player.Position = new Vector2(toTile.X * Game1.tileSize, toTile.Y * Game1.tileSize);
player.FacingDirection = (int)facingDirection;
player.setMovingInFacingDirection();
}
}
/// <summary>Create a pixel texture that can be stretched and colorized for display.</summary>
private static Texture2D CreatePixel()
{
Texture2D texture = new Texture2D(Game1.graphics.GraphicsDevice, 1, 1);
texture.SetData([Color.White]);
return texture;
}
/// <summary>Draw the debug overlay to the screen.</summary>
/// <param name="batch">The sprite batch being drawn.</param>
/// <param name="font">The font with which to render text.</param>
/// <param name="pixel">A pixel texture that can be stretched and colorized for display.</param>
private void DrawOverlay(SpriteBatch batch, SpriteFont font, Texture2D pixel)
{
var viewport = Game1.uiMode ? Game1.uiViewport : Game1.viewport;
int mouseX = Game1.getMouseX();
int mouseY = Game1.getMouseY();
// draw debug info at cursor position
{
// generate debug text
string[] lines = this.GetDebugInfo().ToArray();
// get text
string text = string.Join(Environment.NewLine, lines.WhereNotNull());
Vector2 textSize = font.MeasureString(text);
const int scrollPadding = 5;
// calculate scroll position
int width = (int)(textSize.X + (scrollPadding * 2) + (CommonHelper.ScrollEdgeSize.X * 2));
int height = (int)(textSize.Y + (scrollPadding * 2) + (CommonHelper.ScrollEdgeSize.Y * 2));
int x = MathHelper.Clamp(mouseX - width, 0, viewport.Width - width);
int y = MathHelper.Clamp(mouseY, 0, viewport.Height - height);
// draw
CommonHelper.DrawScroll(batch, new Vector2(x, y), textSize, out Vector2 contentPos, out _, padding: scrollPadding);
batch.DrawString(font, text, new Vector2(contentPos.X, contentPos.Y), Color.Black);
}
// draw cursor crosshairs
batch.Draw(pixel, new Rectangle(0, mouseY - 1, viewport.Width, 3), Color.Black * 0.5f);
batch.Draw(pixel, new Rectangle(mouseX - 1, 0, 3, viewport.Height), Color.Black * 0.5f);
}
/// <summary>Get debug info for the current context.</summary>
private IEnumerable<string> GetDebugInfo()
{
// location
if (Game1.currentLocation is { } location)
{
Vector2 tile = TileHelper.GetTileFromCursor();
yield return $"{I18n.Label_Tile()}: {tile.X}, {tile.Y}";
yield return $"{I18n.Label_Location()}: {location.Name}";
}
// menu
if (Game1.activeClickableMenu is { } menu)
{
Type menuType = menu.GetType();
Type? submenuType = this.GetSubmenu(menu)?.GetType();
string? vanillaNamespace = typeof(TitleMenu).Namespace;
yield return $"{I18n.Label_Menu()}: {(menuType.Namespace == vanillaNamespace ? menuType.Name : menuType.FullName)}";
if (submenuType != null)
yield return $"{I18n.Label_Submenu()}: {(submenuType.Namespace == vanillaNamespace ? submenuType.Name : submenuType.FullName)}";
switch (menu)
{
case DialogueBox dialogue:
{
string? dialogueKey = dialogue.characterDialogue?.TranslationKey;
if (!string.IsNullOrWhiteSpace(dialogueKey))
yield return $"{I18n.Label_Dialogue()}: {dialogueKey}";
}
break;
case ShopMenu shopMenu:
if (!string.IsNullOrWhiteSpace(shopMenu.ShopId))
yield return $"{I18n.Label_ShopId()}: {shopMenu.ShopId}";
break;
}
}
// minigame
if (Game1.currentMinigame is { } minigame)
{
Type minigameType = minigame.GetType();
string? vanillaNamespace = typeof(AbigailGame).Namespace;
yield return $"{I18n.Label_Minigame()}: {(minigameType.Namespace == vanillaNamespace ? minigameType.Name : minigameType.FullName)}";
}
// event
if (Game1.CurrentEvent is { } curEvent)
{
double progress = curEvent.CurrentCommand / (double)curEvent.eventCommands.Length;
if (curEvent.isFestival)
yield return $"{I18n.Label_FestivalName()}: {curEvent.FestivalName}";
yield return $"{I18n.Label_EventId()}: {curEvent.id}";
if (curEvent is { isFestival: false, CurrentCommand: >= 0 } && curEvent.CurrentCommand < curEvent.eventCommands.Length)
yield return $"{I18n.Label_EventScript()}: {curEvent.GetCurrentCommand()} ({(int)(progress * 100)}%)";
}
// music
if (Game1.currentSong is { Name: not null, IsPlaying: true } song)
yield return $"{I18n.Label_Song()}: {song.Name}";
}
/// <summary>Get the submenu for the current menu, if any.</summary>
/// <param name="menu">The submenu.</param>
private IClickableMenu? GetSubmenu(IClickableMenu menu)
{
return menu switch
{
GameMenu gameMenu => gameMenu.pages[gameMenu.currentTab],
TitleMenu => TitleMenu.subMenu,
_ => this.BetterGameMenu?.GetCurrentPage(menu)
};
}
}