From 49cf84910ec416910de7336c0c4b04735a9f7950 Mon Sep 17 00:00:00 2001 From: Aredjay Date: Thu, 2 Jul 2026 23:54:46 -0700 Subject: [PATCH 1/5] v3.5.0: fix NPC schedules, monster health, mine spawn-in-wall, save dropped items - Fix villagers freezing or walking through walls/water after loading a mid-day save. Vanilla precomputes each NPC's daily route from their morning position and replays it without collision checks; after a mid-day reload NPCs weren't where those routes expected. Villagers now get a fresh route to their current schedule destination computed from the tile they actually stand on (using the game's own schedule pathfinding), with the clock held back via ignoreScheduleToday until positions are restored, instead of the previous TryLoadSchedule() call (which reset schedule state) racing the clock advance. - Stop stripping vanilla monsters before a mid-day save. The mod's own cleanMonsters() was deleting every monster from the save file (the game's real save code never touches them); reloading meant any fight in progress reset to full health or vanished, letting players save-scum through combat. Only monster types from other mods' assemblies are still stripped-and-restored in-session, since those aren't covered by the base game's XmlInclude list and would crash the save otherwise. - Fix RestoreMonsters() only clearing its tracking dictionary on one code path, which threw an ArgumentException on a location's second mid-day save of a session; add a null guard for the dictionary and the Forest lookup. - Validate the player's saved tile against the actual location before warping on load, using the game's own recursiveFindOpenTileForCharacter (the same recovery it uses for a stale mail/warp target). Mine and Volcano Dungeon floors regenerate a new random layout every time they're entered and were never part of the save file to begin with, so a saved tile could land inside solid rock in the new layout. - Preserve single-item ground debris (loot, quest items, tools/weapons, unpicked forage) across a mid-day save via a new DebrisData model and GetDebris/RestoreDebris pair in SaveManager, reconstructing dropped items through the game's own ItemRegistry factory on load. Loose resource chunks from a tool swing are out of scope (re-swingable, not an exploit). - Stop overwriting Game1.weatherForTomorrow at save time; it deleted rain forecasts and corrupted weather on festival days. - Block mid-day saves with remote players connected; the vanilla save menu's ready-check barrier can never complete mid-day, which hard-froze multiplayer sessions. Add a save-in-progress guard against re-triggering a mid-day save while one is already running. - Guard OnSaveLoaded/LoadData against farmhands connecting (they'd warp to the host's saved position) and against missing/corrupted save data (would otherwise null-ref on load). - Skip hidden off-map NPCs (Marlon at -42,-42) in saved position data. - Bump ModBuildConfig 4.1.1 -> 4.4.0; fix CI workflow's dotnet-version (5.0.x -> 6.0.x) to match the net6.0 target. Co-Authored-By: Claude Fable 5 --- .github/workflows/dotnet.yml | 2 +- Framework/Model/DebrisData.cs | 11 ++ Framework/Model/PlayerData.cs | 1 + Framework/SaveManager.cs | 289 ++++++++++++++++++++++++++++------ README.md | 37 +++++ SaveAnywhere.cs | 51 ++++-- SaveAnywhere.csproj | 2 +- manifest.json | 2 +- 8 files changed, 336 insertions(+), 59 deletions(-) create mode 100644 Framework/Model/DebrisData.cs diff --git a/.github/workflows/dotnet.yml b/.github/workflows/dotnet.yml index 552a6b7..028c912 100644 --- a/.github/workflows/dotnet.yml +++ b/.github/workflows/dotnet.yml @@ -18,7 +18,7 @@ jobs: - name: Setup .NET uses: actions/setup-dotnet@v3 with: - dotnet-version: 5.0.x + dotnet-version: 6.0.x - name: Restore dependencies run: dotnet restore - name: Build diff --git a/Framework/Model/DebrisData.cs b/Framework/Model/DebrisData.cs new file mode 100644 index 0000000..40e78e5 --- /dev/null +++ b/Framework/Model/DebrisData.cs @@ -0,0 +1,11 @@ +namespace SaveAnywhere.Framework.Model +{ + public sealed record DebrisData( + string Map, + int X, + int Y, + string QualifiedItemId, + int Stack, + int Quality + ); +} diff --git a/Framework/Model/PlayerData.cs b/Framework/Model/PlayerData.cs index b35e528..aa6fd36 100644 --- a/Framework/Model/PlayerData.cs +++ b/Framework/Model/PlayerData.cs @@ -11,5 +11,6 @@ public class PlayerData public PositionData[] Position { get; init; } public bool IsCharacterSwimming { get; init; } + public DebrisData[] Debris { get; init; } } } \ No newline at end of file diff --git a/Framework/SaveManager.cs b/Framework/SaveManager.cs index d04c46d..81fcf0c 100644 --- a/Framework/SaveManager.cs +++ b/Framework/SaveManager.cs @@ -24,6 +24,7 @@ public class SaveManager private bool _waitingToSave; private static bool _middaysaving; + public bool IsSaving => _waitingToSave || _middaysaving; public SaveManager(IModHelper helper, Action onLoaded) { @@ -49,7 +50,12 @@ public void Update() return; Game1.newDaySync = new NewDaySynchronizer(); Game1.newDaySync.start(); - Game1.weatherForTomorrow = Game1.getWeatherModificationsForDate(Game1.Date, Game1.weatherForTomorrow); + // NOTE: do NOT touch Game1.weatherForTomorrow here. It was already rolled + // by last night's real day transition; getWeatherModificationsForDate is + // only valid during that transition (when Date is the day being entered). + // Calling it with today's date forced tomorrow to Sun on the 1st of a + // month / early game (deleting rain forecasts) and to "Festival" on + // festival days. _currentSaveMenu = new SaveGameMenu(); SaveComplete += CurrentSaveMenu_SaveComplete; Game1.activeClickableMenu = _currentSaveMenu; @@ -83,6 +89,8 @@ public bool saveDataExists() public void BeginSaveData() { + if (IsSaving) return; // guard re-entrancy + BeforeSave?.Invoke(this, EventArgs.Empty); foreach (var customSavingBegin in BeforeCustomSavingBegins) customSavingBegin.Value?.Invoke(); @@ -112,7 +120,8 @@ public void BeginSaveData() DrinkBuff = drinkdata, FoodBuff = fooddata, Position = GetPosition().ToArray(), - IsCharacterSwimming = Game1.player.swimming.Value + IsCharacterSwimming = Game1.player.swimming.Value, + Debris = GetDebris() }); var tempShippingBin = new Chest(true, new Vector2(-100, -100)); foreach (var item in farm.getShippingBin(Game1.player)) @@ -139,21 +148,30 @@ public void LoadData() var data = _helper.Data.ReadSaveData("midday-save") ?? _helper.Data.ReadJsonFile(RelativeDataPath); if (data == null) + { ClearData(); + return; + } - - foreach (var item in (Game1.getFarm().getObjectAtTile(-100, -100) as Chest).Items) + // Restore the shipping bin from the temp chest (if it survived the save). + var tempShippingBin = Game1.getFarm().getObjectAtTile(-100, -100) as Chest; + if (tempShippingBin != null) { - if (item.modData["farmerSelling"] == Game1.player.UniqueMultiplayerID.ToString()) + foreach (var item in tempShippingBin.Items) { - if (item.modData["last"] == "true") - Game1.getFarm().lastItemShipped = item; - Game1.getFarm().getShippingBin(Game1.player).Add(item); + if (item == null) continue; + if (item.modData["farmerSelling"] == Game1.player.UniqueMultiplayerID.ToString()) + { + if (item.modData["last"] == "true") + Game1.getFarm().lastItemShipped = item; + Game1.getFarm().getShippingBin(Game1.player).Add(item); + } } + Game1.getFarm().removeObject(new Vector2(-100, -100), false); } - Game1.getFarm().removeObject(new Vector2(-100, -100), false); SetPositions(data.Position, data.Time); + RestoreDebris(data.Debris); // if (data.OtherBuffs != null) // foreach (var buff in data.OtherBuffs) // { @@ -260,56 +278,235 @@ private IEnumerable GetPosition() int facingDirection1 = player.FacingDirection; yield return new PositionData(name1, map1, tile1.X, tile1.Y, facingDirection1); - foreach (var allCharacter in Utility.getAllCharacters()) - yield return new PositionData(allCharacter.Name, allCharacter.currentLocation.Name, - allCharacter.TilePoint.X, allCharacter.TilePoint.Y, - allCharacter.FacingDirection); + foreach (var npc in Utility.getAllCharacters()) + { + if (npc?.currentLocation == null) continue; + // The game parks some hidden NPCs off-map (e.g. Marlon at -42,-42); + // don't record or restore those. + if (npc.TilePoint.X < 0 || npc.TilePoint.Y < 0) continue; + + var npcMap = npc.currentLocation.uniqueName.Value; + if (string.IsNullOrEmpty(npcMap)) + npcMap = npc.currentLocation.Name; + + yield return new PositionData(npc.Name, npcMap, + npc.TilePoint.X, npc.TilePoint.Y, npc.FacingDirection); + } } private void SetPositions(PositionData[] position, int time) { - Game1.player.faceDirection(position[0].FacingDirection); + if (position == null || position.Length == 0) return; + + var log = SaveAnywhere.Instance.Monitor; + + // Restore player first (warpFarmer handles its own screen transition). + var playerPos = position[0]; + int px = playerPos.X, py = playerPos.Y; + + // Mine/Volcano Dungeon levels are never part of the save file (they + // live only in a runtime cache, never added to Game1.locations), so + // reloading into one always regenerates a brand-new random layout. + // The saved tile can be solid rock in the new layout. Resolve the + // target location BEFORE warping (warpFarmer's location change is + // applied on a later tick, so currentLocation can't be trusted right + // after the call) and nudge to the nearest open tile if needed — the + // same tool the game itself uses to recover a stale mail/warp target. + // Short-circuits instantly when the saved tile is already open, so + // it's cheap to run unconditionally, not just for regenerated levels. + var targetLoc = Game1.getLocationFromName(playerPos.Map); + if (targetLoc != null) + { + var open = Utility.recursiveFindOpenTileForCharacter( + Game1.player, targetLoc, new Vector2(px, py), 20, allowOffMap: false); + if (open != Vector2.Zero) + { + px = (int)open.X; + py = (int)open.Y; + } + else + { + log.Log($"[SA] No open tile near ({playerPos.X},{playerPos.Y}) in {playerPos.Map}; using saved tile", + LogLevel.Warn); + } + } + + Game1.warpFarmer(playerPos.Map, px, py, playerPos.FacingDirection); + + // Restore each villager's saved tile and clear stale movement state from + // the vanilla morning load BEFORE the clock moves. checkSchedule() runs on + // every 10-minute tick and fires the day's precomputed routes; those route + // points assume the NPC walked there from its morning position, and an NPC + // standing anywhere else beelines to the first point straight through + // walls (PathFindController does no collision checks). ignoreScheduleToday + // makes checkSchedule a no-op while SafelySetTime fast-forwards. + var restored = new List(); + foreach (var npc in Utility.getAllCharacters()) + { + var pos = position.FirstOrDefault(p => p.Name == npc.Name); + if (pos == null) continue; + + try + { + Game1.warpCharacter(npc, pos.Map, new Point(pos.X, pos.Y)); + npc.faceDirection(pos.FacingDirection); + + if (!npc.IsVillager) continue; - Game1.fadeScreenToBlack(); - Game1.warpFarmer(position[0].Map, position[0].X, position[0].Y, false); + npc.Halt(); + npc.controller = null; + npc.temporaryController = null; + npc.queuedSchedulePaths?.Clear(); + npc.ignoreScheduleToday = true; + restored.Add(npc); + } + catch (Exception ex) + { + log.Log($"[SA] Exception restoring {npc?.Name}: {ex.Message}", LogLevel.Error); + } + } + + // Advance the clock; lights, music and location state update naturally + // while villager schedules stay suppressed. SafelySetTime(time); - foreach (var allCharacter in Utility.getAllCharacters()) + // Give each villager a route to its CURRENT schedule destination computed + // fresh from the tile it actually stands on (collision-valid and cross-map, + // same pathfinding the engine uses when parsing schedules), then let + // checkSchedule() take over as if the route were the engine's own. + foreach (var npc in restored) { - var pos = position.FirstOrDefault(p => p.Name == allCharacter.Name); - if (pos == null) continue; - Game1.warpCharacter(allCharacter, pos.Map, new Point(pos.X, pos.Y)); - allCharacter.faceDirection(pos.FacingDirection); - if (!allCharacter.IsVillager) continue; - allCharacter.TryLoadSchedule(); - if (allCharacter.Schedule == null) continue; - var dest = allCharacter.Schedule - .OrderBy(pair => pair.Key).LastOrDefault(data => data.Key < time); - - if (dest.Key == 0) continue; - var endingLocation = dest.Value.targetLocationName; - allCharacter.Schedule.Remove(dest.Key); - - var schedule = allCharacter.pathfindToNextScheduleLocation( - allCharacter.ScheduleKey, pos.Map, pos.X, pos.Y, - endingLocation, - dest.Value.targetTile.X, - dest.Value.targetTile.Y, - dest.Value.facingDirection, - dest.Value.endOfRouteBehavior, - dest.Value.endOfRouteMessage); - - allCharacter.update(Game1.currentGameTime, Utility.getGameLocationOfCharacter(allCharacter)); - allCharacter.Schedule.TryAdd(time, schedule); - if (allCharacter.doingEndOfRouteAnimation.Value || allCharacter.controller == null) - continue; - allCharacter.controller.pathToEndPoint = schedule.route; - allCharacter.controller.update(Game1.currentGameTime); + try + { + npc.ignoreScheduleToday = false; + npc.followSchedule = true; + if (npc.Schedule == null) continue; + + // Last schedule entry that should have started by savedTime. + int lastPassed = 0; + foreach (var k in npc.Schedule.Keys.OrderBy(x => x)) + { + if (k > time) break; + lastPassed = k; + } + + // Past entries are handled below; stop the engine replaying them. + npc.lastAttemptedSchedule = time; + + if (lastPassed == 0) continue; // schedule hasn't started yet today + + var seg = npc.Schedule[lastPassed]; + + // Destination = the segment's target tile; fall back to the canned + // route's final point (targetTile can be left at -1,-1). + Point dest = seg.targetTile; + if (dest.X <= 0 && dest.Y <= 0 && seg.route != null && seg.route.Count > 0) + dest = seg.route.Last(); + if (dest.X <= 0 && dest.Y <= 0) continue; + + bool atDest = npc.currentLocation?.Name == seg.targetLocationName + && npc.TilePoint.X == dest.X && npc.TilePoint.Y == dest.Y; + + var fresh = npc.pathfindToNextScheduleLocation( + npc.ScheduleKey, + npc.currentLocation.Name, npc.TilePoint.X, npc.TilePoint.Y, + seg.targetLocationName, dest.X, dest.Y, + seg.facingDirection, seg.endOfRouteBehavior, seg.endOfRouteMessage); + fresh.time = lastPassed; + + if (!atDest && (fresh.route == null || fresh.route.Count == 0)) + { + // No walkable route from here (unreachable interior, missing + // warp path): snap to the destination so the NEXT schedule + // entry starts from the tile its canned route expects. + Game1.warpCharacter(npc, seg.targetLocationName, new Point(dest.X, dest.Y)); + npc.faceDirection(seg.facingDirection); + npc.previousEndPoint = dest; + continue; + } + + // Queue it and fire through the engine so endOfRouteBehavior, + // previousEndPoint and facing are wired exactly like a normal + // schedule move. An empty route (already at destination) makes + // checkSchedule run the end-of-route behavior immediately. + npc.queuedSchedulePaths?.Clear(); + npc.queuedSchedulePaths?.Add(fresh); + npc.checkSchedule(Game1.timeOfDay); + } + catch (Exception ex) + { + log.Log($"[SA] Exception scheduling {npc?.Name}: {ex.Message}", LogLevel.Error); + } } Utility.fixAllAnimals(); } + // ── Dropped items ──────────────────────────────────────────────────── + // GameLocation.debris is intentionally excluded from the vanilla save + // (normal saves only happen after the ground is already clear at + // night), so a mid-day save loses anything not yet picked up. Only + // single-item drops (a real Item, not a loose resource chunk from a + // tool swing — those are re-swingable, not worth the complexity of + // modeling per-chunk physics) are preserved here and respawned on + // load via the game's own item factory. + + private static DebrisData[] GetDebris() + { + try + { + var list = new List(); + foreach (var location in Game1.locations) + { + var mapName = !string.IsNullOrEmpty(location.uniqueName.Value) + ? location.uniqueName.Value : location.Name; + + foreach (var d in location.debris) + { + if (d?.item == null) continue; + if (d.debrisType.Value != Debris.DebrisType.OBJECT + && d.debrisType.Value != Debris.DebrisType.ARCHAEOLOGY) continue; + + var chunk = d.Chunks.FirstOrDefault(); + if (chunk == null) continue; + var tile = chunk.position.Value / 64f; + + int quality = (d.item as StardewValley.Object)?.Quality ?? 0; + list.Add(new DebrisData(mapName, (int)tile.X, (int)tile.Y, + d.item.QualifiedItemId, d.item.Stack, quality)); + } + } + return list.ToArray(); + } + catch + { + return Array.Empty(); + } + } + + private static void RestoreDebris(DebrisData[] debrisDatas) + { + if (debrisDatas == null) return; + try + { + foreach (var dd in debrisDatas) + { + var location = Game1.getLocationFromName(dd.Map); + if (location == null) continue; // stale/invalid modded location + + var item = ItemRegistry.Create(dd.QualifiedItemId, dd.Stack, dd.Quality, allowNull: true); + if (item == null) continue; // removed/invalid item id + + var origin = new Vector2(dd.X * 64f + 32f, dd.Y * 64f + 32f); + location.debris.Add(new Debris(item, origin)); + } + } + catch + { + // Debris restore is best-effort; don't crash the load. + } + } + private void RemoveLegacyDataForThisPlayer() { diff --git a/README.md b/README.md index 668800f..c4c4e75 100644 --- a/README.md +++ b/README.md @@ -21,6 +21,43 @@ game), if you have GMCM use it instead. #### Created by Omegasis, Aredjay, and RealSweetPanda +### Changelog + +#### 3.5.0 + +- **Fixed villagers freezing or walking through walls/water after loading a mid-day save.** The game precomputes each + NPC's daily route from their morning position and replays it without collision checks; after a mid-day reload NPCs + were not where those routes expected, which froze them or sent them cutting through walls, water, and map edges + (and could make them vanish into unreachable spots). Villagers now get a fresh path to their current schedule + destination computed from the tile they actually stand on, using the game's own schedule pathfinding, and + villagers who already reached their destination resume their idle behavior (reading, standing at the counter, + etc.) instead of standing blank. +- **Fixed monster health resetting on reload — this was letting players save-scum out of fights.** The mod was + stripping every monster from the world before each mid-day save; the game's own save code never touches monsters, + so this was purely the mod deleting them from the file. Reloading meant any monster you were fighting came back + at full health or vanished entirely. Vanilla monsters now save and reload with their current health. Monster + types added by other mods are still excluded from the save file (some aren't safe to serialize), so they behave + as before. +- **Fixed the player sometimes spawning inside solid rock in mines and the Volcano Dungeon.** Those floors are + randomly regenerated every time you enter them and were never part of the save file to begin with, so reloading + mid-mine puts you in a brand-new layout — your saved spot could now be a wall. The mod checks for this and moves + you to the nearest open tile using the same recovery the game uses for its own stale warp points. +- **Dropped items no longer disappear on reload.** Something you just chopped, looted, or knocked loose that's + still sitting on the ground used to vanish, because the game doesn't normally expect the ground to have anything + on it when a save happens. Single-item drops (loot, quest items, tools/weapons, unpicked forage) are now + preserved. Loose resource chunks from a tool swing (wood/stone/coal not yet walked over) aren't — just re-swing + the same node. +- **Fixed saving changing tomorrow's weather** (e.g. deleting rain, or corrupting the forecast when saving on a + festival day). +- **Fixed multiplayer hang:** mid-day saving with farmhands connected froze the game on the saving screen forever; + the mod now blocks the save with a clear message instead. +- Fixed a crash (`ArgumentException`) on the second mid-day save of a session in some cases. +- Fixed a possible crash on load if the mid-day save data was missing or corrupted. +- Farmhands connecting to a host no longer get warped to the host's saved position. +- Hidden off-map NPCs (e.g. Marlon) are no longer saved/restored. +- Removed a redundant double screen-fade when loading a mid-day save. +- Updated build tooling for current SMAPI (no deprecated APIs). + ### Notes The mod should now work with map extension mods, modded characters, modded items, etc in the newest update. If it diff --git a/SaveAnywhere.cs b/SaveAnywhere.cs index 20c553d..b8bcf3c 100644 --- a/SaveAnywhere.cs +++ b/SaveAnywhere.cs @@ -60,7 +60,9 @@ private void BuildConfigMenu(object sender, GameLaunchedEventArgs e) private void OnSaveLoaded(object sender, SaveLoadedEventArgs e) { - // ShouldResetSchedules = true; + // Farmhands also get SaveLoaded when connecting; only the host restores + // world state (positions, clock, schedules). + if (!Context.IsMainPlayer) return; if (SaveManager.saveDataExists()) SaveManager.LoadData(); } @@ -78,9 +80,17 @@ private void OnUpdateTicked(object sender, UpdateTickedEventArgs e) } + // Vanilla monsters are left in place so the real save serializes them + // with their current health (vanilla's own save code never touches + // monsters). Only monster types from OTHER mods' assemblies are + // stripped before the save and re-added immediately after — those + // aren't covered by the base game's XmlInclude list and would crash + // the save's XmlSerializer with an "unexpected type" error otherwise. public void cleanMonsters() { _monsters = new Dictionary>(); + var baseAssembly = typeof(Monster).Assembly; + foreach (var location in Game1.locations) { if (location is Forest) @@ -91,28 +101,38 @@ public void cleanMonsters() } _monsters.Add(location, new List()); foreach (var character in location.characters) - if (character is Monster monster) - { - Monitor.Log(character.Name); + if (character is Monster monster && monster.GetType().Assembly != baseAssembly) _monsters[location].Add(monster); - } foreach (var monster in _monsters[location]) location.characters.Remove(monster); } - - } public void RestoreMonsters() { + if (_monsters == null) return; + foreach (var monster1 in _monsters) foreach (var monster2 in monster1.Value) monster1.Key.addCharacter(monster2); + var forest = Utility.fuzzyLocationSearch("Forest"); - if (Game1.year <= 2 || Game1.isRaining || Utility.isFestivalDay(Game1.dayOfMonth, Game1.season) || forest.getCharacterFromName("TrashBear") != null || NetWorldState.checkAnywhereForWorldStateID("trashBearDone")) - return; - forest.characters.Add( new TrashBear()); + if (forest != null + && Game1.year > 2 + && !Game1.isRaining + && !Utility.isFestivalDay(Game1.dayOfMonth, Game1.season) + && forest.getCharacterFromName("TrashBear") == null + && !NetWorldState.checkAnywhereForWorldStateID("trashBearDone")) + { + forest.characters.Add(new TrashBear()); + } + + // Always clear, regardless of the TrashBear branch above — this used to + // only run when TrashBear conditions were met, so on the next mid-day + // save cleanMonsters() would call _monsters.Add() on a location key that + // was never cleared, throwing an ArgumentException on the second save of + // a session. _monsters.Clear(); } @@ -120,8 +140,19 @@ private void OnButtonPressed(object sender, ButtonPressedEventArgs e) { if (!Context.IsPlayerFree || e.Button != _config.SaveKey || Game1.eventUp || Game1.isFestival()) return; + if (SaveManager.IsSaving) return; + if (Game1.client == null) { + // The vanilla save menu waits on a ready-check barrier that includes + // every online farmer; farmhands never join it for a mid-day save, so + // the game would hang on "saving" forever with remote players connected. + if (Context.HasRemotePlayers) + { + Game1.addHUDMessage(new HUDMessage("Can't save mid-day while other players are connected.", 3)); + return; + } + if (Game1.player.currentLocation.characters.Any(x => x is Junimo)) Game1.addHUDMessage(new HUDMessage("The spirits don't want you to save here.", 3)); else diff --git a/SaveAnywhere.csproj b/SaveAnywhere.csproj index a195ce1..279f052 100644 --- a/SaveAnywhere.csproj +++ b/SaveAnywhere.csproj @@ -7,7 +7,7 @@ - + diff --git a/manifest.json b/manifest.json index 430cee2..23427c3 100644 --- a/manifest.json +++ b/manifest.json @@ -1,7 +1,7 @@ { "Name": "Save Anywhere Redux", "Author": "Open Source", - "Version": "3.3.0", + "Version": "3.5.0", "Description": "This mod allows you to save your game at any time, anywhere.", "UniqueID": "Omegasis.SaveAnywhere", "EntryDll": "SaveAnywhere.dll", From 83d1d56c2f2003ae8129188507b76254cbc950e9 Mon Sep 17 00:00:00 2001 From: Aredjay Date: Thu, 2 Jul 2026 23:56:54 -0700 Subject: [PATCH 2/5] Ignore local CLAUDE.md working notes --- .gitignore | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.gitignore b/.gitignore index 9c52ea1..a483f14 100644 --- a/.gitignore +++ b/.gitignore @@ -4,3 +4,5 @@ bin/ obj/ + +CLAUDE.md From a146725c700795dc67072ba4511afc153a0fc768 Mon Sep 17 00:00:00 2001 From: Aredjay Date: Fri, 3 Jul 2026 00:28:46 -0700 Subject: [PATCH 3/5] Fix dropped-item capture (missed building interiors), skip save animation MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - GetDebris()/RestoreDebris() iterated Game1.locations directly, which does NOT include building interiors (farmhouse, sheds, coops, barns, cabins) — those live under each Building's own .indoors and are only reachable via Utility.ForEachLocation(includeInteriors: true). Any item dropped indoors was silently invisible to the debris save/restore, which is almost certainly why it looked like dropped items weren't being preserved at all. Also switched from one try/catch wrapping the entire scan (a single bad debris object silently zeroed out everything) to per-item/per-location handling, and added Trace-level [SA] logging of capture/restore counts for the next round of testing. - Skip SaveGameMenu's ~1.5s "has been saved" sparkle-text hold during a mid-day save. The actual file write is done the moment Game1.game1.IsSaving flips back to false; at that point we now set the menu's public `quit` field early (the same externally-settable field vanilla itself uses to close the menu when a client times out), so its own update() closes it on the very next tick instead of waiting out the decorative animation. Doesn't touch the actual save-driving or multiplayer-sync logic at all, just skips the cosmetic wait. Co-Authored-By: Claude Fable 5 --- Framework/SaveManager.cs | 131 ++++++++++++++++++++++++++++++--------- 1 file changed, 101 insertions(+), 30 deletions(-) diff --git a/Framework/SaveManager.cs b/Framework/SaveManager.cs index 81fcf0c..4597649 100644 --- a/Framework/SaveManager.cs +++ b/Framework/SaveManager.cs @@ -23,6 +23,7 @@ public class SaveManager private static SaveGameMenu _currentSaveMenu; private bool _waitingToSave; private static bool _middaysaving; + private bool _sawSaveInProgress; public bool IsSaving => _waitingToSave || _middaysaving; @@ -46,6 +47,27 @@ public SaveManager(IModHelper helper, Action onLoaded) public void Update() { + // SaveGameMenu holds a ~1.5s "has been saved" sparkle-text animation + // after the actual file write finishes — it's vanilla's end-of-night + // screen, and looks like a full day transition even though the clock + // never advances for a mid-day save. The real write is done the moment + // Game1.game1.IsSaving flips back to false (SaveGameMenu sets that + // itself); at that point we set its public `quit` flag early — the + // same externally-settable field vanilla itself uses to close the menu + // when a client times out — so its own update() closes it on the very + // next tick instead of waiting out the decorative hold. This doesn't + // touch the actual save/cleanup logic at all, just skips the wait. + if (_currentSaveMenu != null) + { + if (Game1.game1.IsSaving) + _sawSaveInProgress = true; + else if (_sawSaveInProgress) + { + _sawSaveInProgress = false; + _currentSaveMenu.quit = true; + } + } + if (!_waitingToSave || Game1.activeClickableMenu != null) return; Game1.newDaySync = new NewDaySynchronizer(); @@ -66,6 +88,7 @@ private void CurrentSaveMenu_SaveComplete(object sender, EventArgs e) { SaveComplete -= CurrentSaveMenu_SaveComplete; _currentSaveMenu = null; + _sawSaveInProgress = false; SaveAnywhere.Instance.RestoreMonsters(); AfterSave?.Invoke(this, EventArgs.Empty); foreach (var keyValuePair in AfterCustomSavingCompleted) @@ -453,58 +476,106 @@ private void SetPositions(PositionData[] position, int time) private static DebrisData[] GetDebris() { - try + var log = SaveAnywhere.Instance.Monitor; + var list = new List(); + + // Game1.locations alone does NOT include building interiors (farmhouse, + // sheds, coops, barns, cabins, etc.) — those are nested under each + // Building's own .indoors, which is exactly why Utility.ForEachLocation + // exists (includeInteriors: true walks them too). Iterating Game1.locations + // directly here silently missed every debris dropped indoors. + // includeGenerated also covers a currently-active mine/volcano floor. + Utility.ForEachLocation(delegate(GameLocation location) { - var list = new List(); - foreach (var location in Game1.locations) + try { var mapName = !string.IsNullOrEmpty(location.uniqueName.Value) ? location.uniqueName.Value : location.Name; foreach (var d in location.debris) { - if (d?.item == null) continue; - if (d.debrisType.Value != Debris.DebrisType.OBJECT - && d.debrisType.Value != Debris.DebrisType.ARCHAEOLOGY) continue; - - var chunk = d.Chunks.FirstOrDefault(); - if (chunk == null) continue; - var tile = chunk.position.Value / 64f; - - int quality = (d.item as StardewValley.Object)?.Quality ?? 0; - list.Add(new DebrisData(mapName, (int)tile.X, (int)tile.Y, - d.item.QualifiedItemId, d.item.Stack, quality)); + try + { + if (d?.item == null) continue; + if (d.debrisType.Value != Debris.DebrisType.OBJECT + && d.debrisType.Value != Debris.DebrisType.ARCHAEOLOGY) continue; + + var chunk = d.Chunks.FirstOrDefault(); + if (chunk == null) continue; + var tile = chunk.position.Value / 64f; + + int quality = (d.item as StardewValley.Object)?.Quality ?? 0; + list.Add(new DebrisData(mapName, (int)tile.X, (int)tile.Y, + d.item.QualifiedItemId, d.item.Stack, quality)); + } + catch (Exception ex) + { + // One bad debris item shouldn't cost every other item on + // the ground; skip just this one and keep going. + log.Log($"[SA] Skipped one debris item in {mapName}: {ex.Message}", LogLevel.Trace); + } } } - return list.ToArray(); - } - catch - { - return Array.Empty(); - } + catch (Exception ex) + { + log.Log($"[SA] Skipped location {location?.Name} while scanning debris: {ex.Message}", LogLevel.Trace); + } + return true; // keep iterating remaining locations + }, includeInteriors: true, includeGenerated: true); + + log.Log($"[SA] Captured {list.Count} debris item(s) for mid-day save", LogLevel.Trace); + return list.ToArray(); } private static void RestoreDebris(DebrisData[] debrisDatas) { - if (debrisDatas == null) return; - try + if (debrisDatas == null || debrisDatas.Length == 0) return; + var log = SaveAnywhere.Instance.Monitor; + + // Game1.getLocationFromName(name) alone doesn't reliably resolve building + // interiors (same gap as GetDebris reading Game1.locations directly), so + // build the lookup the same way the data was captured — via + // Utility.ForEachLocation — to guarantee symmetry between save and load. + var byName = new Dictionary(); + Utility.ForEachLocation(delegate(GameLocation location) { - foreach (var dd in debrisDatas) + var name = !string.IsNullOrEmpty(location.uniqueName.Value) + ? location.uniqueName.Value : location.Name; + if (!string.IsNullOrEmpty(name)) + byName[name] = location; + return true; + }, includeInteriors: true, includeGenerated: true); + + int restored = 0; + foreach (var dd in debrisDatas) + { + try { - var location = Game1.getLocationFromName(dd.Map); - if (location == null) continue; // stale/invalid modded location + if (!byName.TryGetValue(dd.Map, out var location)) + { + log.Log($"[SA] Debris location '{dd.Map}' not found on load; skipping {dd.QualifiedItemId}", LogLevel.Trace); + continue; + } var item = ItemRegistry.Create(dd.QualifiedItemId, dd.Stack, dd.Quality, allowNull: true); - if (item == null) continue; // removed/invalid item id + if (item == null) + { + log.Log($"[SA] Debris item '{dd.QualifiedItemId}' no longer exists; skipping", LogLevel.Trace); + continue; + } var origin = new Vector2(dd.X * 64f + 32f, dd.Y * 64f + 32f); location.debris.Add(new Debris(item, origin)); + restored++; + } + catch (Exception ex) + { + // One bad entry shouldn't cost every other item; skip just this one. + log.Log($"[SA] Exception restoring debris '{dd.QualifiedItemId}': {ex.Message}", LogLevel.Trace); } } - catch - { - // Debris restore is best-effort; don't crash the load. - } + + log.Log($"[SA] Restored {restored}/{debrisDatas.Length} debris item(s) after mid-day load", LogLevel.Trace); } From 5ae450a8a1917e60181621fc8500edb1a77e1099 Mon Sep 17 00:00:00 2001 From: Aredjay Date: Fri, 3 Jul 2026 08:43:33 -0700 Subject: [PATCH 4/5] Preserve resource piles (wood/stone/coal) dropped by chopping/mining The debris fix so far only covered debris backed by a live .item (regular single-item drops) -- confirmed via decompile that resource piles from a tool swing never get one; InitializeResource/InitializeItem only set the raw itemId string for those, since Debris.collect() treats each chunk as a separate 1-unit pickup regardless of any stack value. This is exactly the case the user hit: chop a tree, save before walking over the wood, reload, wood is gone. - DebrisData gains an IsResourcePile flag. - GetDebris no longer requires a live .item; it also captures resource piles via the raw itemId field, using the remaining chunk count (not a stack value, which collect() would ignore) as the quantity. - RestoreDebris reconstructs a resource pile as that many separate single-item Debris objects (matching the original one-chunk-per-pickup behavior) instead of one item with a big stack, which would have silently discarded everything past the first pickup. Co-Authored-By: Claude Fable 5 --- Framework/Model/DebrisData.cs | 3 +- Framework/SaveManager.cs | 68 +++++++++++++++++++++++++++++------ 2 files changed, 60 insertions(+), 11 deletions(-) diff --git a/Framework/Model/DebrisData.cs b/Framework/Model/DebrisData.cs index 40e78e5..3af3adc 100644 --- a/Framework/Model/DebrisData.cs +++ b/Framework/Model/DebrisData.cs @@ -6,6 +6,7 @@ public sealed record DebrisData( int Y, string QualifiedItemId, int Stack, - int Quality + int Quality, + bool IsResourcePile ); } diff --git a/Framework/SaveManager.cs b/Framework/SaveManager.cs index 4597649..dd309b6 100644 --- a/Framework/SaveManager.cs +++ b/Framework/SaveManager.cs @@ -496,17 +496,39 @@ private static DebrisData[] GetDebris() { try { - if (d?.item == null) continue; - if (d.debrisType.Value != Debris.DebrisType.OBJECT - && d.debrisType.Value != Debris.DebrisType.ARCHAEOLOGY) continue; + if (d == null) continue; + + // Resource piles (wood/stone/coal left over from chopping + // a tree or mining a rock) never get a live `.item` — + // InitializeResource/InitializeItem only set the raw + // itemId string for those, since each chunk is collected + // as a separate pickup (see collect() below). Regular + // single-item drops (loot, quest items, tools/weapons, + // forage) DO have a real `.item`. Filtering on "has a + // resolvable id" (rather than a specific DebrisType) + // naturally excludes purely decorative debris (splinters, + // floating damage numbers, letters) which never get one. + bool hasRealItem = d.item != null; + var qualifiedId = hasRealItem ? d.item.QualifiedItemId : d.itemId.Value; + if (string.IsNullOrEmpty(qualifiedId)) continue; var chunk = d.Chunks.FirstOrDefault(); if (chunk == null) continue; var tile = chunk.position.Value / 64f; + // A real dropped item's own stack (the game creates one + // Debris per item when dropping a stack, so this is + // almost always 1), or — for a resource pile — how many + // chunks are still waiting to be picked up. collect() + // gives exactly 1 unit per chunk for resource piles + // regardless of any stack value, which RestoreDebris + // below accounts for via IsResourcePile. + int amount = hasRealItem ? d.item.Stack : d.Chunks.Count; + if (amount <= 0) amount = 1; + int quality = (d.item as StardewValley.Object)?.Quality ?? 0; list.Add(new DebrisData(mapName, (int)tile.X, (int)tile.Y, - d.item.QualifiedItemId, d.item.Stack, quality)); + qualifiedId, amount, quality, !hasRealItem)); } catch (Exception ex) { @@ -557,15 +579,41 @@ private static void RestoreDebris(DebrisData[] debrisDatas) continue; } - var item = ItemRegistry.Create(dd.QualifiedItemId, dd.Stack, dd.Quality, allowNull: true); - if (item == null) + var origin = new Vector2(dd.X * 64f + 32f, dd.Y * 64f + 32f); + + if (dd.IsResourcePile) { - log.Log($"[SA] Debris item '{dd.QualifiedItemId}' no longer exists; skipping", LogLevel.Trace); - continue; + // Resource piles give exactly 1 unit per chunk on pickup + // (Debris.collect() ignores stack size when there's no live + // `.item`), so recreate that many separate single-item + // debris rather than one item with a big stack — otherwise + // walking over the pile once would only give back 1 unit + // and silently discard the rest. + int placed = 0; + for (int i = 0; i < dd.Stack; i++) + { + var piece = ItemRegistry.Create(dd.QualifiedItemId, 1, dd.Quality, allowNull: true); + if (piece == null) break; // invalid/removed id; stop trying more + location.debris.Add(new Debris(piece, origin)); + placed++; + } + if (placed == 0) + { + log.Log($"[SA] Debris item '{dd.QualifiedItemId}' no longer exists; skipping", LogLevel.Trace); + continue; + } + } + else + { + var item = ItemRegistry.Create(dd.QualifiedItemId, dd.Stack, dd.Quality, allowNull: true); + if (item == null) + { + log.Log($"[SA] Debris item '{dd.QualifiedItemId}' no longer exists; skipping", LogLevel.Trace); + continue; + } + location.debris.Add(new Debris(item, origin)); } - var origin = new Vector2(dd.X * 64f + 32f, dd.Y * 64f + 32f); - location.debris.Add(new Debris(item, origin)); restored++; } catch (Exception ex) From c1e340dc2ed97b0319f4593aa083be70acf3c960 Mon Sep 17 00:00:00 2001 From: Aredjay Date: Sat, 4 Jul 2026 11:16:34 -0700 Subject: [PATCH 5/5] Update changelog: resource piles are preserved too, note animation skip --- README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index c4c4e75..426c26a 100644 --- a/README.md +++ b/README.md @@ -44,13 +44,14 @@ game), if you have GMCM use it instead. you to the nearest open tile using the same recovery the game uses for its own stale warp points. - **Dropped items no longer disappear on reload.** Something you just chopped, looted, or knocked loose that's still sitting on the ground used to vanish, because the game doesn't normally expect the ground to have anything - on it when a save happens. Single-item drops (loot, quest items, tools/weapons, unpicked forage) are now - preserved. Loose resource chunks from a tool swing (wood/stone/coal not yet walked over) aren't — just re-swing - the same node. + on it when a save happens. This covers both single-item drops (loot, quest items, tools/weapons, unpicked forage) + and loose resource piles (wood/stone/coal left over from chopping a tree or mining a rock), indoors or out. - **Fixed saving changing tomorrow's weather** (e.g. deleting rain, or corrupting the forecast when saving on a festival day). - **Fixed multiplayer hang:** mid-day saving with farmhands connected froze the game on the saving screen forever; the mod now blocks the save with a clear message instead. +- Skipped the few-second "has been saved" animation for a mid-day save — that screen is vanilla's end-of-night + transition, and doesn't make sense when the clock isn't actually advancing to the next day. - Fixed a crash (`ArgumentException`) on the second mid-day save of a session in some cases. - Fixed a possible crash on load if the mid-day save data was missing or corrupted. - Farmhands connecting to a host no longer get warped to the host's saved position.