summaryrefslogtreecommitdiff
path: root/src/SMAPI/Framework/SGame.cs
diff options
context:
space:
mode:
Diffstat (limited to 'src/SMAPI/Framework/SGame.cs')
-rw-r--r--src/SMAPI/Framework/SGame.cs810
1 files changed, 37 insertions, 773 deletions
diff --git a/src/SMAPI/Framework/SGame.cs b/src/SMAPI/Framework/SGame.cs
index abb766f2..8efc8996 100644
--- a/src/SMAPI/Framework/SGame.cs
+++ b/src/SMAPI/Framework/SGame.cs
@@ -1,29 +1,15 @@
using System;
-using System.Collections;
-using System.Collections.Concurrent;
-using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
-using System.Linq;
using System.Text;
-using System.Threading;
using System.Threading.Tasks;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Netcode;
-using StardewModdingAPI.Enums;
-using StardewModdingAPI.Events;
-using StardewModdingAPI.Framework.Content;
using StardewModdingAPI.Framework.Events;
using StardewModdingAPI.Framework.Input;
-using StardewModdingAPI.Framework.Networking;
-using StardewModdingAPI.Framework.PerformanceMonitoring;
using StardewModdingAPI.Framework.Reflection;
-using StardewModdingAPI.Framework.Rendering;
-using StardewModdingAPI.Framework.StateTracking.Comparers;
-using StardewModdingAPI.Framework.StateTracking.Snapshots;
using StardewModdingAPI.Framework.Utilities;
-using StardewModdingAPI.Toolkit.Serialization;
using StardewValley;
using StardewValley.BellsAndWhistles;
using StardewValley.Events;
@@ -42,107 +28,46 @@ namespace StardewModdingAPI.Framework
/*********
** Fields
*********/
- /****
- ** SMAPI state
- ****/
/// <summary>Encapsulates monitoring and logging for SMAPI.</summary>
private readonly Monitor Monitor;
- /// <summary>Encapsulates monitoring and logging on the game's behalf.</summary>
- private readonly IMonitor MonitorForGame;
-
/// <summary>Manages SMAPI events for mods.</summary>
private readonly EventManager Events;
- /// <summary>Tracks the installed mods.</summary>
- private readonly ModRegistry ModRegistry;
-
- /// <summary>Manages deprecation warnings.</summary>
- private readonly DeprecationManager DeprecationManager;
-
- /// <summary>Tracks performance metrics.</summary>
- private readonly PerformanceMonitor PerformanceMonitor;
-
/// <summary>The maximum number of consecutive attempts SMAPI should make to recover from a draw error.</summary>
private readonly Countdown DrawCrashTimer = new Countdown(60); // 60 ticks = roughly one second
- /// <summary>The maximum number of consecutive attempts SMAPI should make to recover from an update error.</summary>
- private readonly Countdown UpdateCrashTimer = new Countdown(60); // 60 ticks = roughly one second
-
- /// <summary>The number of ticks until SMAPI should notify mods that the game has loaded.</summary>
- /// <remarks>Skipping a few frames ensures the game finishes initializing the world before mods try to change it.</remarks>
- private readonly Countdown AfterLoadTimer = new Countdown(5);
-
- /// <summary>Whether custom content was removed from the save data to avoid a crash.</summary>
- private bool IsSaveContentRemoved;
-
- /// <summary>Whether the game is saving and SMAPI has already raised <see cref="IGameLoopEvents.Saving"/>.</summary>
- private bool IsBetweenSaveEvents;
-
- /// <summary>Whether the game is creating the save file and SMAPI has already raised <see cref="IGameLoopEvents.SaveCreating"/>.</summary>
- private bool IsBetweenCreateEvents;
-
- /// <summary>A callback to invoke the first time *any* game content manager loads an asset.</summary>
- private readonly Action OnLoadingFirstAsset;
-
- /// <summary>A callback to invoke after the game finishes initializing.</summary>
- private readonly Action OnGameInitialized;
-
- /// <summary>A callback to invoke when the game exits.</summary>
- private readonly Action OnGameExiting;
-
/// <summary>Simplifies access to private game code.</summary>
private readonly Reflector Reflection;
- /// <summary>Encapsulates access to SMAPI core translations.</summary>
- private readonly Translator Translator;
-
- /// <summary>Propagates notification that SMAPI should exit.</summary>
- private readonly CancellationTokenSource CancellationToken;
-
- /****
- ** Game state
- ****/
- /// <summary>Monitors the entire game state for changes.</summary>
- private WatcherCore Watchers;
-
- /// <summary>A snapshot of the current <see cref="Watchers"/> state.</summary>
- private readonly WatcherSnapshot WatcherSnapshot = new WatcherSnapshot();
-
- /// <summary>Whether post-game-startup initialization has been performed.</summary>
- private bool IsInitialized;
-
- /// <summary>Whether the next content manager requested by the game will be for <see cref="Game1.content"/>.</summary>
- private bool NextContentManagerIsMain;
+ /// <summary>Immediately exit the game without saving. This should only be invoked when an irrecoverable fatal error happens that risks save corruption or game-breaking bugs.</summary>
+ private readonly Action<string> ExitGameImmediately;
/*********
** Accessors
*********/
- /// <summary>Static state to use while <see cref="Game1"/> is initializing, which happens before the <see cref="SGame"/> constructor runs.</summary>
- internal static SGameConstructorHack ConstructorHack { get; set; }
-
- /// <summary>The number of update ticks which have already executed. This is similar to <see cref="Game1.ticks"/>, but incremented more consistently for every tick.</summary>
- internal static uint TicksElapsed { get; private set; }
+ /// <summary>Manages input visible to the game.</summary>
+ public static SInputState Input => (SInputState)Game1.input;
- /// <summary>SMAPI's content manager.</summary>
- public ContentCoordinator ContentCore { get; private set; }
+ /// <summary>The game's core multiplayer utility.</summary>
+ public static SMultiplayer Multiplayer => (SMultiplayer)Game1.multiplayer;
- /// <summary>Manages console commands.</summary>
- public CommandManager CommandManager { get; } = new CommandManager();
+ /// <summary>The game background task which initializes a new day.</summary>
+ public static Task NewDayTask => Game1._newDayTask;
- /// <summary>Manages input visible to the game.</summary>
- public SInputState Input => (SInputState)Game1.input;
+ /// <summary>Construct a content manager to read game content files.</summary>
+ /// <remarks>This must be static because the game accesses it before the <see cref="SGame"/> constructor is called.</remarks>
+ public static Func<IServiceProvider, string, LocalizedContentManager> CreateContentManagerImpl;
- /// <summary>The game's core multiplayer utility.</summary>
- public SMultiplayer Multiplayer => (SMultiplayer)Game1.multiplayer;
+ /// <summary>Raised after the game finishes loading its initial content.</summary>
+ public event Action OnGameContentLoaded;
- /// <summary>A list of queued commands to execute.</summary>
- /// <remarks>This property must be threadsafe, since it's accessed from a separate console input thread.</remarks>
- public ConcurrentQueue<string> CommandQueue { get; } = new ConcurrentQueue<string>();
+ /// <summary>Raised before the game exits.</summary>
+ public event Action OnGameExiting;
- /// <summary>Asset interceptors added or removed since the last tick.</summary>
- private readonly List<AssetInterceptorChange> ReloadAssetInterceptorsQueue = new List<AssetInterceptorChange>();
+ /// <summary>Raised when the game is updating its state (roughly 60 times per second).</summary>
+ public event Action<GameTime, Action> OnGameUpdating;
/*********
@@ -150,74 +75,35 @@ namespace StardewModdingAPI.Framework
*********/
/// <summary>Construct an instance.</summary>
/// <param name="monitor">Encapsulates monitoring and logging for SMAPI.</param>
- /// <param name="monitorForGame">Encapsulates monitoring and logging on the game's behalf.</param>
/// <param name="reflection">Simplifies access to private game code.</param>
- /// <param name="translator">Encapsulates access to arbitrary translations.</param>
/// <param name="eventManager">Manages SMAPI events for mods.</param>
- /// <param name="jsonHelper">Encapsulates SMAPI's JSON file parsing.</param>
- /// <param name="modRegistry">Tracks the installed mods.</param>
- /// <param name="deprecationManager">Manages deprecation warnings.</param>
- /// <param name="performanceMonitor">Tracks performance metrics.</param>
- /// <param name="onGameInitialized">A callback to invoke after the game finishes initializing.</param>
- /// <param name="onGameExiting">A callback to invoke when the game exits.</param>
- /// <param name="cancellationToken">Propagates notification that SMAPI should exit.</param>
- /// <param name="logNetworkTraffic">Whether to log network traffic.</param>
- internal SGame(Monitor monitor, IMonitor monitorForGame, Reflector reflection, Translator translator, EventManager eventManager, JsonHelper jsonHelper, ModRegistry modRegistry, DeprecationManager deprecationManager, PerformanceMonitor performanceMonitor, Action onGameInitialized, Action onGameExiting, CancellationTokenSource cancellationToken, bool logNetworkTraffic)
+ /// <param name="modHooks">Handles mod hooks provided by the game.</param>
+ /// <param name="multiplayer">The core multiplayer logic.</param>
+ /// <param name="exitGameImmediately">Immediately exit the game without saving. This should only be invoked when an irrecoverable fatal error happens that risks save corruption or game-breaking bugs.</param>
+ internal SGame(Monitor monitor, Reflector reflection, EventManager eventManager, SModHooks modHooks, SMultiplayer multiplayer, Action<string> exitGameImmediately)
{
- this.OnLoadingFirstAsset = SGame.ConstructorHack.OnLoadingFirstAsset;
- SGame.ConstructorHack = null;
-
- // check expectations
- if (this.ContentCore == null)
- throw new InvalidOperationException($"The game didn't initialize its first content manager before SMAPI's {nameof(SGame)} constructor. This indicates an incompatible lifecycle change.");
-
// init XNA
Game1.graphics.GraphicsProfile = GraphicsProfile.HiDef;
+ // hook into game
+ Game1.input = new SInputState();
+ Game1.multiplayer = multiplayer;
+ Game1.hooks = modHooks;
+ Game1.locations = new ObservableCollection<GameLocation>();
+
// init SMAPI
this.Monitor = monitor;
- this.MonitorForGame = monitorForGame;
this.Events = eventManager;
- this.ModRegistry = modRegistry;
this.Reflection = reflection;
- this.Translator = translator;
- this.DeprecationManager = deprecationManager;
- this.PerformanceMonitor = performanceMonitor;
- this.OnGameInitialized = onGameInitialized;
- this.OnGameExiting = onGameExiting;
- Game1.input = new SInputState();
- Game1.multiplayer = new SMultiplayer(monitor, eventManager, jsonHelper, modRegistry, reflection, this.OnModMessageReceived, logNetworkTraffic);
- Game1.hooks = new SModHooks(this.OnNewDayAfterFade);
- this.CancellationToken = cancellationToken;
-
- // init observables
- Game1.locations = new ObservableCollection<GameLocation>();
+ this.ExitGameImmediately = exitGameImmediately;
}
/// <summary>Load content when the game is launched.</summary>
protected override void LoadContent()
{
- // load content
base.LoadContent();
- Game1.mapDisplayDevice = new SDisplayDevice(Game1.content, this.GraphicsDevice);
- // log GPU info
-#if SMAPI_FOR_WINDOWS
- this.Monitor.Log($"Running on GPU: {this.GraphicsDevice?.Adapter?.Description ?? "<unknown>"}");
-#endif
- }
-
- /// <summary>Initialize just before the game's first update tick.</summary>
- private void InitializeAfterGameStarted()
- {
- // set initial state
- this.Input.TrueUpdate();
-
- // init watchers
- this.Watchers = new WatcherCore(this.Input);
-
- // raise callback
- this.OnGameInitialized();
+ this.OnGameContentLoaded?.Invoke();
}
/// <summary>Perform cleanup logic when the game exits.</summary>
@@ -226,639 +112,25 @@ namespace StardewModdingAPI.Framework
/// <remarks>This overrides the logic in <see cref="Game1.exitEvent"/> to let SMAPI clean up before exit.</remarks>
protected override void OnExiting(object sender, EventArgs args)
{
- Game1.multiplayer.Disconnect(StardewValley.Multiplayer.DisconnectType.ClosedGame);
this.OnGameExiting?.Invoke();
}
- /// <summary>A callback invoked before <see cref="Game1.newDayAfterFade"/> runs.</summary>
- protected void OnNewDayAfterFade()
- {
- this.Events.DayEnding.RaiseEmpty();
- }
-
- /// <summary>A callback invoked when a mod message is received.</summary>
- /// <param name="message">The message to deliver to applicable mods.</param>
- private void OnModMessageReceived(ModMessageModel message)
- {
- // get mod IDs to notify
- HashSet<string> modIDs = new HashSet<string>(message.ToModIDs ?? this.ModRegistry.GetAll().Select(p => p.Manifest.UniqueID), StringComparer.OrdinalIgnoreCase);
- if (message.FromPlayerID == Game1.player?.UniqueMultiplayerID)
- modIDs.Remove(message.FromModID); // don't send a broadcast back to the sender
-
- // raise events
- this.Events.ModMessageReceived.Raise(new ModMessageReceivedEventArgs(message), mod => mod != null && modIDs.Contains(mod.Manifest.UniqueID));
- }
-
- /// <summary>A callback invoked when custom content is removed from the save data to avoid a crash.</summary>
- internal void OnSaveContentRemoved()
- {
- this.IsSaveContentRemoved = true;
- }
-
- /// <summary>A callback invoked when the game's low-level load stage changes.</summary>
- /// <param name="newStage">The new load stage.</param>
- internal void OnLoadStageChanged(LoadStage newStage)
- {
- // nothing to do
- if (newStage == Context.LoadStage)
- return;
-
- // update data
- LoadStage oldStage = Context.LoadStage;
- Context.LoadStage = newStage;
- this.Monitor.VerboseLog($"Context: load stage changed to {newStage}");
- if (newStage == LoadStage.None)
- {
- this.Monitor.Log("Context: returned to title", LogLevel.Trace);
- this.OnReturnedToTitle();
- }
-
- // raise events
- this.Events.LoadStageChanged.Raise(new LoadStageChangedEventArgs(oldStage, newStage));
- if (newStage == LoadStage.None)
- this.Events.ReturnedToTitle.RaiseEmpty();
- }
-
- /// <summary>A callback invoked when a mod adds or removes an asset interceptor.</summary>
- /// <param name="mod">The mod which added or removed interceptors.</param>
- /// <param name="added">The added interceptors.</param>
- /// <param name="removed">The removed interceptors.</param>
- internal void OnAssetInterceptorsChanged(IModMetadata mod, IEnumerable added, IEnumerable removed)
- {
- if (added != null)
- {
- foreach (object instance in added)
- this.ReloadAssetInterceptorsQueue.Add(new AssetInterceptorChange(mod, instance, wasAdded: true));
- }
- if (removed != null)
- {
- foreach (object instance in removed)
- this.ReloadAssetInterceptorsQueue.Add(new AssetInterceptorChange(mod, instance, wasAdded: false));
- }
- }
-
- /// <summary>Perform cleanup when the game returns to the title screen.</summary>
- private void OnReturnedToTitle()
- {
- this.Multiplayer.CleanupOnMultiplayerExit();
-
- if (!(Game1.mapDisplayDevice is SDisplayDevice))
- Game1.mapDisplayDevice = new SDisplayDevice(Game1.content, this.GraphicsDevice);
- }
-
- /// <summary>Constructor a content manager to read XNB files.</summary>
+ /// <summary>Construct a content manager to read game content files.</summary>
/// <param name="serviceProvider">The service provider to use to locate services.</param>
/// <param name="rootDirectory">The root directory to search for content.</param>
protected override LocalizedContentManager CreateContentManager(IServiceProvider serviceProvider, string rootDirectory)
{
- // Game1._temporaryContent initializing from SGame constructor
- // NOTE: this method is called before the SGame constructor runs. Don't depend on anything being initialized at this point.
- if (this.ContentCore == null)
- {
- this.ContentCore = new ContentCoordinator(serviceProvider, rootDirectory, Thread.CurrentThread.CurrentUICulture, SGame.ConstructorHack.Monitor, SGame.ConstructorHack.Reflection, SGame.ConstructorHack.JsonHelper, this.OnLoadingFirstAsset ?? SGame.ConstructorHack?.OnLoadingFirstAsset);
- this.NextContentManagerIsMain = true;
- return this.ContentCore.CreateGameContentManager("Game1._temporaryContent");
- }
+ if (SGame.CreateContentManagerImpl == null)
+ throw new InvalidOperationException($"The {nameof(SGame)}.{nameof(SGame.CreateContentManagerImpl)} must be set.");
- // Game1.content initializing from LoadContent
- if (this.NextContentManagerIsMain)
- {
- this.NextContentManagerIsMain = false;
- return this.ContentCore.MainContentManager;
- }
-
- // any other content manager
- return this.ContentCore.CreateGameContentManager("(generated)");
+ return SGame.CreateContentManagerImpl(serviceProvider, rootDirectory);
}
- /// <summary>The method called when the game is updating its state. This happens roughly 60 times per second.</summary>
+ /// <summary>The method called when the game is updating its state (roughly 60 times per second).</summary>
/// <param name="gameTime">A snapshot of the game timing state.</param>
protected override void Update(GameTime gameTime)
{
- var events = this.Events;
-
- try
- {
- this.DeprecationManager.PrintQueued();
- this.PerformanceMonitor.PrintQueuedAlerts();
-
- /*********
- ** First-tick initialization
- *********/
- if (!this.IsInitialized)
- {
- this.IsInitialized = true;
- this.InitializeAfterGameStarted();
- }
-
- /*********
- ** Update input
- *********/
- // This should *always* run, even when suppressing mod events, since the game uses
- // this too. For example, doing this after mod event suppression would prevent the
- // user from doing anything on the overnight shipping screen.
- SInputState inputState = this.Input;
- if (this.IsActive)
- inputState.TrueUpdate();
-
- /*********
- ** Special cases
- *********/
- // Abort if SMAPI is exiting.
- if (this.CancellationToken.IsCancellationRequested)
- {
- this.Monitor.Log("SMAPI shutting down: aborting update.", LogLevel.Trace);
- return;
- }
-
- // Run async tasks synchronously to avoid issues due to mod events triggering
- // concurrently with game code.
- bool saveParsed = false;
- if (Game1.currentLoader != null)
- {
- this.Monitor.Log("Game loader synchronizing...", LogLevel.Trace);
- while (Game1.currentLoader?.MoveNext() == true)
- {
- // raise load stage changed
- switch (Game1.currentLoader.Current)
- {
- case 20 when (!saveParsed && SaveGame.loaded != null):
- saveParsed = true;
- this.OnLoadStageChanged(LoadStage.SaveParsed);
- break;
-
- case 36:
- this.OnLoadStageChanged(LoadStage.SaveLoadedBasicInfo);
- break;
-
- case 50:
- this.OnLoadStageChanged(LoadStage.SaveLoadedLocations);
- break;
-
- default:
- if (Game1.gameMode == Game1.playingGameMode)
- this.OnLoadStageChanged(LoadStage.Preloaded);
- break;
- }
- }
-
- Game1.currentLoader = null;
- this.Monitor.Log("Game loader done.", LogLevel.Trace);
- }
- if (Game1._newDayTask?.Status == TaskStatus.Created)
- {
- this.Monitor.Log("New day task synchronizing...", LogLevel.Trace);
- Game1._newDayTask.RunSynchronously();
- this.Monitor.Log("New day task done.", LogLevel.Trace);
- }
-
- // While a background task is in progress, the game may make changes to the game
- // state while mods are running their code. This is risky, because data changes can
- // conflict (e.g. collection changed during enumeration errors) and data may change
- // unexpectedly from one mod instruction to the next.
- //
- // Therefore we can just run Game1.Update here without raising any SMAPI events. There's
- // a small chance that the task will finish after we defer but before the game checks,
- // which means technically events should be raised, but the effects of missing one
- // update tick are negligible and not worth the complications of bypassing Game1.Update.
- if (Game1._newDayTask != null || Game1.gameMode == Game1.loadingMode)
- {
- events.UnvalidatedUpdateTicking.RaiseEmpty();
- SGame.TicksElapsed++;
- base.Update(gameTime);
- events.UnvalidatedUpdateTicked.RaiseEmpty();
- return;
- }
-
- // Raise minimal events while saving.
- // While the game is writing to the save file in the background, mods can unexpectedly
- // fail since they don't have exclusive access to resources (e.g. collection changed
- // during enumeration errors). To avoid problems, events are not invoked while a save
- // is in progress. It's safe to raise SaveEvents.BeforeSave as soon as the menu is
- // opened (since the save hasn't started yet), but all other events should be suppressed.
- if (Context.IsSaving)
- {
- // raise before-create
- if (!Context.IsWorldReady && !this.IsBetweenCreateEvents)
- {
- this.IsBetweenCreateEvents = true;
- this.Monitor.Log("Context: before save creation.", LogLevel.Trace);
- events.SaveCreating.RaiseEmpty();
- }
-
- // raise before-save
- if (Context.IsWorldReady && !this.IsBetweenSaveEvents)
- {
- this.IsBetweenSaveEvents = true;
- this.Monitor.Log("Context: before save.", LogLevel.Trace);
- events.Saving.RaiseEmpty();
- }
-
- // suppress non-save events
- events.UnvalidatedUpdateTicking.RaiseEmpty();
- SGame.TicksElapsed++;
- base.Update(gameTime);
- events.UnvalidatedUpdateTicked.RaiseEmpty();
- return;
- }
-
- /*********
- ** Reload assets when interceptors are added/removed
- *********/
- if (this.ReloadAssetInterceptorsQueue.Any())
- {
- // get unique interceptors
- AssetInterceptorChange[] interceptors = this.ReloadAssetInterceptorsQueue
- .GroupBy(p => p.Instance, new ObjectReferenceComparer<object>())
- .Select(p => p.First())
- .ToArray();
- this.ReloadAssetInterceptorsQueue.Clear();
-
- // log summary
- this.Monitor.Log("Invalidating cached assets for new editors & loaders...");
- this.Monitor.Log(
- " changed: "
- + string.Join(", ",
- interceptors
- .GroupBy(p => p.Mod)
- .OrderBy(p => p.Key.DisplayName)
- .Select(modGroup =>
- $"{modGroup.Key.DisplayName} ("
- + string.Join(", ", modGroup.GroupBy(p => p.WasAdded).ToDictionary(p => p.Key, p => p.Count()).Select(p => $"{(p.Key ? "added" : "removed")} {p.Value}"))
- + ")"
- )
- )
- );
-
- // reload affected assets
- this.ContentCore.InvalidateCache(asset => interceptors.Any(p => p.CanIntercept(asset)));
- }
-
- /*********
- ** Execute commands
- *********/
- while (this.CommandQueue.TryDequeue(out string rawInput))
- {
- // parse command
- string name;
- string[] args;
- Command command;
- try
- {
- if (!this.CommandManager.TryParse(rawInput, out name, out args, out command))
- {
- this.Monitor.Log("Unknown command; type 'help' for a list of available commands.", LogLevel.Error);
- continue;
- }
- }
- catch (Exception ex)
- {
- this.Monitor.Log($"Failed parsing that command:\n{ex.GetLogSummary()}", LogLevel.Error);
- continue;
- }
-
- // execute command
- try
- {
- command.Callback.Invoke(name, args);
- }
- catch (Exception ex)
- {
- if (command.Mod != null)
- command.Mod.LogAsMod($"Mod failed handling that command:\n{ex.GetLogSummary()}", LogLevel.Error);
- else
- this.Monitor.Log($"Failed handling that command:\n{ex.GetLogSummary()}", LogLevel.Error);
- }
- }
-
- /*********
- ** Update context
- *********/
- bool wasWorldReady = Context.IsWorldReady;
- if ((Context.IsWorldReady && !Context.IsSaveLoaded) || Game1.exitToTitle)
- {
- Context.IsWorldReady = false;
- this.AfterLoadTimer.Reset();
- }
- else if (Context.IsSaveLoaded && this.AfterLoadTimer.Current > 0 && Game1.currentLocation != null)
- {
- if (Game1.dayOfMonth != 0) // wait until new-game intro finishes (world not fully initialized yet)
- this.AfterLoadTimer.Decrement();
- Context.IsWorldReady = this.AfterLoadTimer.Current == 0;
- }
-
- /*********
- ** Update watchers
- ** (Watchers need to be updated, checked, and reset in one go so we can detect any changes mods make in event handlers.)
- *********/
- this.Watchers.Update();
- this.WatcherSnapshot.Update(this.Watchers);
- this.Watchers.Reset();
- WatcherSnapshot state = this.WatcherSnapshot;
-
- /*********
- ** Display in-game warnings
- *********/
- // save content removed
- if (this.IsSaveContentRemoved && Context.IsWorldReady)
- {
- this.IsSaveContentRemoved = false;
- Game1.addHUDMessage(new HUDMessage(this.Translator.Get("warn.invalid-content-removed"), HUDMessage.error_type));
- }
-
- /*********
- ** Pre-update events
- *********/
- {
- /*********
- ** Save created/loaded events
- *********/
- if (this.IsBetweenCreateEvents)
- {
- // raise after-create
- this.IsBetweenCreateEvents = false;
- this.Monitor.Log($"Context: after save creation, starting {Game1.currentSeason} {Game1.dayOfMonth} Y{Game1.year}.", LogLevel.Trace);
- this.OnLoadStageChanged(LoadStage.CreatedSaveFile);
- events.SaveCreated.RaiseEmpty();
- }
- if (this.IsBetweenSaveEvents)
- {
- // raise after-save
- this.IsBetweenSaveEvents = false;
- this.Monitor.Log($"Context: after save, starting {Game1.currentSeason} {Game1.dayOfMonth} Y{Game1.year}.", LogLevel.Trace);
- events.Saved.RaiseEmpty();
- events.DayStarted.RaiseEmpty();
- }
-
- /*********
- ** Locale changed events
- *********/
- if (state.Locale.IsChanged)
- this.Monitor.Log($"Context: locale set to {state.Locale.New}.", LogLevel.Trace);
-
- /*********
- ** Load / return-to-title events
- *********/
- if (wasWorldReady && !Context.IsWorldReady)
- this.OnLoadStageChanged(LoadStage.None);
- else if (Context.IsWorldReady && Context.LoadStage != LoadStage.Ready)
- {
- // print context
- string context = $"Context: loaded save '{Constants.SaveFolderName}', starting {Game1.currentSeason} {Game1.dayOfMonth} Y{Game1.year}, locale set to {this.ContentCore.Language}.";
- if (Context.IsMultiplayer)
- {
- int onlineCount = Game1.getOnlineFarmers().Count();
- context += $" {(Context.IsMainPlayer ? "Main player" : "Farmhand")} with {onlineCount} {(onlineCount == 1 ? "player" : "players")} online.";
- }
- else
- context += " Single-player.";
- this.Monitor.Log(context, LogLevel.Trace);
-
- // raise events
- this.OnLoadStageChanged(LoadStage.Ready);
- events.SaveLoaded.RaiseEmpty();
- events.DayStarted.RaiseEmpty();
- }
-
- /*********
- ** Window events
- *********/
- // Here we depend on the game's viewport instead of listening to the Window.Resize
- // event because we need to notify mods after the game handles the resize, so the
- // game's metadata (like Game1.viewport) are updated. That's a bit complicated
- // since the game adds & removes its own handler on the fly.
- if (state.WindowSize.IsChanged)
- {
- if (this.Monitor.IsVerbose)
- this.Monitor.Log($"Events: window size changed to {state.WindowSize.New}.", LogLevel.Trace);
-
- events.WindowResized.Raise(new WindowResizedEventArgs(state.WindowSize.Old, state.WindowSize.New));
- }
-
- /*********
- ** Input events (if window has focus)
- *********/
- if (this.IsActive)
- {
- // raise events
- bool isChatInput = Game1.IsChatting || (Context.IsMultiplayer && Context.IsWorldReady && Game1.activeClickableMenu == null && Game1.currentMinigame == null && inputState.IsAnyDown(Game1.options.chatButton));
- if (!isChatInput)
- {
- ICursorPosition cursor = this.Input.CursorPosition;
-
- // raise cursor moved event
- if (state.Cursor.IsChanged)
- events.CursorMoved.Raise(new CursorMovedEventArgs(state.Cursor.Old, state.Cursor.New));
-
- // raise mouse wheel scrolled
- if (state.MouseWheelScroll.IsChanged)
- {
- if (this.Monitor.IsVerbose)
- this.Monitor.Log($"Events: mouse wheel scrolled to {state.MouseWheelScroll.New}.", LogLevel.Trace);
- events.MouseWheelScrolled.Raise(new MouseWheelScrolledEventArgs(cursor, state.MouseWheelScroll.Old, state.MouseWheelScroll.New));
- }
-
- // raise input button events
- foreach (var pair in inputState.LastButtonStates)
- {
- SButton button = pair.Key;
- SButtonState status = pair.Value;
-
- if (status == SButtonState.Pressed)
- {
- if (this.Monitor.IsVerbose)
- this.Monitor.Log($"Events: button {button} pressed.", LogLevel.Trace);
-
- events.ButtonPressed.Raise(new ButtonPressedEventArgs(button, cursor, inputState));
- }
- else if (status == SButtonState.Released)
- {
- if (this.Monitor.IsVerbose)
- this.Monitor.Log($"Events: button {button} released.", LogLevel.Trace);
-
- events.ButtonReleased.Raise(new ButtonReleasedEventArgs(button, cursor, inputState));
- }
- }
- }
- }
-
- /*********
- ** Menu events
- *********/
- if (state.ActiveMenu.IsChanged)
- {
- if (this.Monitor.IsVerbose)
- this.Monitor.Log($"Context: menu changed from {state.ActiveMenu.Old?.GetType().FullName ?? "none"} to {state.ActiveMenu.New?.GetType().FullName ?? "none"}.", LogLevel.Trace);
-
- // raise menu events
- events.MenuChanged.Raise(new MenuChangedEventArgs(state.ActiveMenu.Old, state.ActiveMenu.New));
- }
-
- /*********
- ** World & player events
- *********/
- if (Context.IsWorldReady)
- {
- bool raiseWorldEvents = !state.SaveID.IsChanged; // don't report changes from unloaded => loaded
-
- // location list changes
- if (state.Locations.LocationList.IsChanged && (events.LocationListChanged.HasListeners() || this.Monitor.IsVerbose))
- {
- var added = state.Locations.LocationList.Added.ToArray();
- var removed = state.Locations.LocationList.Removed.ToArray();
-
- if (this.Monitor.IsVerbose)
- {
- string addedText = added.Any() ? string.Join(", ", added.Select(p => p.Name)) : "none";
- string removedText = removed.Any() ? string.Join(", ", removed.Select(p => p.Name)) : "none";
- this.Monitor.Log($"Context: location list changed (added {addedText}; removed {removedText}).", LogLevel.Trace);
- }
-
- events.LocationListChanged.Raise(new LocationListChangedEventArgs(added, removed));
- }
-
- // raise location contents changed
- if (raiseWorldEvents)
- {
- foreach (LocationSnapshot locState in state.Locations.Locations)
- {
- var location = locState.Location;
-
- // buildings changed
- if (locState.Buildings.IsChanged)
- events.BuildingListChanged.Raise(new BuildingListChangedEventArgs(location, locState.Buildings.Added, locState.Buildings.Removed));
-
- // debris changed
- if (locState.Debris.IsChanged)
- events.DebrisListChanged.Raise(new DebrisListChangedEventArgs(location, locState.Debris.Added, locState.Debris.Removed));
-
- // large terrain features changed
- if (locState.LargeTerrainFeatures.IsChanged)
- events.LargeTerrainFeatureListChanged.Raise(new LargeTerrainFeatureListChangedEventArgs(location, locState.LargeTerrainFeatures.Added, locState.LargeTerrainFeatures.Removed));
-
- // NPCs changed
- if (locState.Npcs.IsChanged)
- events.NpcListChanged.Raise(new NpcListChangedEventArgs(location, locState.Npcs.Added, locState.Npcs.Removed));
-
- // objects changed
- if (locState.Objects.IsChanged)
- events.ObjectListChanged.Raise(new ObjectListChangedEventArgs(location, locState.Objects.Added, locState.Objects.Removed));
-
- // chest items changed
- if (events.ChestInventoryChanged.HasListeners())
- {
- foreach (var pair in locState.ChestItems)
- {
- SnapshotItemListDiff diff = pair.Value;
- events.ChestInventoryChanged.Raise(new ChestInventoryChangedEventArgs(pair.Key, location, added: diff.Added, removed: diff.Removed, quantityChanged: diff.QuantityChanged));
- }
- }
-
- // terrain features changed
- if (locState.TerrainFeatures.IsChanged)
- events.TerrainFeatureListChanged.Raise(new TerrainFeatureListChangedEventArgs(location, locState.TerrainFeatures.Added, locState.TerrainFeatures.Removed));
- }
- }
-
- // raise time changed
- if (raiseWorldEvents && state.Time.IsChanged)
- events.TimeChanged.Raise(new TimeChangedEventArgs(state.Time.Old, state.Time.New));
-
- // raise player events
- if (raiseWorldEvents)
- {
- PlayerSnapshot playerState = state.CurrentPlayer;
- Farmer player = playerState.Player;
-
- // raise current location changed
- if (playerState.Location.IsChanged)
- {
- if (this.Monitor.IsVerbose)
- this.Monitor.Log($"Context: set location to {playerState.Location.New}.", LogLevel.Trace);
-
- events.Warped.Raise(new WarpedEventArgs(player, playerState.Location.Old, playerState.Location.New));
- }
-
- // raise player leveled up a skill
- foreach (var pair in playerState.Skills)
- {
- if (!pair.Value.IsChanged)
- continue;
-
- if (this.Monitor.IsVerbose)
- this.Monitor.Log($"Events: player skill '{pair.Key}' changed from {pair.Value.Old} to {pair.Value.New}.", LogLevel.Trace);
-
- events.LevelChanged.Raise(new LevelChangedEventArgs(player, pair.Key, pair.Value.Old, pair.Value.New));
- }
-
- // raise player inventory changed
- if (playerState.Inventory.IsChanged)
- {
- var inventory = playerState.Inventory;
-
- if (this.Monitor.IsVerbose)
- this.Monitor.Log("Events: player inventory changed.", LogLevel.Trace);
- events.InventoryChanged.Raise(new InventoryChangedEventArgs(player, added: inventory.Added, removed: inventory.Removed, quantityChanged: inventory.QuantityChanged));
- }
- }
- }
-
- /*********
- ** Game update
- *********/
- // game launched
- bool isFirstTick = SGame.TicksElapsed == 0;
- if (isFirstTick)
- {
- Context.IsGameLaunched = true;
- events.GameLaunched.Raise(new GameLaunchedEventArgs());
- }
-
- // preloaded
- if (Context.IsSaveLoaded && Context.LoadStage != LoadStage.Loaded && Context.LoadStage != LoadStage.Ready && Game1.dayOfMonth != 0)
- this.OnLoadStageChanged(LoadStage.Loaded);
- }
-
- /*********
- ** Game update tick
- *********/
- {
- bool isOneSecond = SGame.TicksElapsed % 60 == 0;
- events.UnvalidatedUpdateTicking.RaiseEmpty();
- events.UpdateTicking.RaiseEmpty();
- if (isOneSecond)
- events.OneSecondUpdateTicking.RaiseEmpty();
- try
- {
- this.Input.ApplyOverrides(); // if mods added any new overrides since the update, process them now
- SGame.TicksElapsed++;
- base.Update(gameTime);
- }
- catch (Exception ex)
- {
- this.MonitorForGame.Log($"An error occured in the base update loop: {ex.GetLogSummary()}", LogLevel.Error);
- }
-
- events.UnvalidatedUpdateTicked.RaiseEmpty();
- events.UpdateTicked.RaiseEmpty();
- if (isOneSecond)
- events.OneSecondUpdateTicked.RaiseEmpty();
- }
-
- /*********
- ** Update events
- *********/
- this.UpdateCrashTimer.Reset();
- }
- catch (Exception ex)
- {
- // log error
- this.Monitor.Log($"An error occured in the overridden update loop: {ex.GetLogSummary()}", LogLevel.Error);
-
- // exit if irrecoverable
- if (!this.UpdateCrashTimer.Decrement())
- this.ExitGameImmediately("The game crashed when updating, and SMAPI was unable to recover the game.");
- }
+ this.OnGameUpdating?.Invoke(gameTime, () => base.Update(gameTime));
}
/// <summary>The method called to draw everything to the screen.</summary>
@@ -890,7 +162,7 @@ namespace StardewModdingAPI.Framework
{
if (Game1.spriteBatch.IsOpen(this.Reflection))
{
- this.Monitor.Log("Recovering sprite batch from error...", LogLevel.Trace);
+ this.Monitor.Log("Recovering sprite batch from error...");
Game1.spriteBatch.End();
}
}
@@ -1316,7 +588,7 @@ namespace StardewModdingAPI.Framework
}
Game1.drawPlayerHeldObject(Game1.player);
}
- label_139:
+ label_139:
if ((Game1.player.UsingTool || Game1.pickingTool) && Game1.player.CurrentTool != null && ((!Game1.player.CurrentTool.Name.Equals("Seeds") || Game1.pickingTool) && (Game1.currentLocation.Map.GetLayer("Front").PickTile(new Location(Game1.player.getStandingX(), (int)Game1.player.Position.Y - 38), Game1.viewport.Size) != null && Game1.currentLocation.Map.GetLayer("Front").PickTile(new Location(Game1.player.getStandingX(), Game1.player.getStandingY()), Game1.viewport.Size) == null)))
Game1.drawTool(Game1.player);
if (Game1.currentLocation.Map.GetLayer("AlwaysFront") != null)
@@ -1604,13 +876,5 @@ namespace StardewModdingAPI.Framework
}
}
}
-
- /// <summary>Immediately exit the game without saving. This should only be invoked when an irrecoverable fatal error happens that risks save corruption or game-breaking bugs.</summary>
- /// <param name="message">The fatal log message.</param>
- private void ExitGameImmediately(string message)
- {
- this.Monitor.LogFatal(message);
- this.CancellationToken.Cancel();
- }
}
}