summaryrefslogtreecommitdiff
path: root/src/SMAPI.Mods.ConsoleCommands/Framework/Commands/World/ClearCommand.cs
blob: ceaeb2789bec0ff56a6570caca9961a82b91c504 (plain)
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
using System;
using System.Linq;
using StardewValley;
using StardewValley.Locations;
using StardewValley.Objects;
using StardewValley.TerrainFeatures;
using SObject = StardewValley.Object;

namespace StardewModdingAPI.Mods.ConsoleCommands.Framework.Commands.World
{
    /// <summary>A command which clears in-game objects.</summary>
    internal class ClearCommand : ConsoleCommand
    {
        /*********
        ** Fields
        *********/
        /// <summary>The valid types that can be cleared.</summary>
        private readonly string[] ValidTypes = { "crops", "debris", "fruit-trees", "furniture", "grass", "trees", "removable", "everything" };

        /// <summary>The resource clump IDs to consider debris.</summary>
        private readonly int[] DebrisClumps = { ResourceClump.stumpIndex, ResourceClump.hollowLogIndex, ResourceClump.meteoriteIndex, ResourceClump.boulderIndex };


        /*********
        ** Public methods
        *********/
        /// <summary>Construct an instance.</summary>
        public ClearCommand()
            : base(
                name: "world_clear",
                description: "Clears in-game entities in a given location.\n\n"
                    + "Usage: world_clear <location> <object type>\n"
                    + " - location: the location name for which to clear objects (like Farm), or 'current' for the current location.\n"
                    + " - object type: the type of object clear. You can specify 'crops', 'debris' (stones/twigs/weeds and dead crops), 'furniture', 'grass', and 'trees' / 'fruit-trees'. You can also specify 'removable' (remove everything that can be removed or destroyed during normal gameplay) or 'everything' (remove everything including permanent bushes)."
            )
        { }

        /// <summary>Handle the command.</summary>
        /// <param name="monitor">Writes messages to the console and log file.</param>
        /// <param name="command">The command name.</param>
        /// <param name="args">The command arguments.</param>
        public override void Handle(IMonitor monitor, string command, ArgumentParser args)
        {
            // check context
            if (!Context.IsWorldReady)
            {
                monitor.Log("You need to load a save to use this command.", LogLevel.Error);
                return;
            }

            // parse arguments
            if (!args.TryGet(0, "location", out string locationName, required: true))
                return;
            if (!args.TryGet(1, "object type", out string type, required: true, oneOf: this.ValidTypes))
                return;

            // get target location
            GameLocation location = Game1.locations.FirstOrDefault(p => p.Name != null && p.Name.Equals(locationName, StringComparison.OrdinalIgnoreCase));
            if (location == null && locationName == "current")
                location = Game1.currentLocation;
            if (location == null)
            {
                string[] locationNames = (from loc in Game1.locations where !string.IsNullOrWhiteSpace(loc.Name) orderby loc.Name select loc.Name).ToArray();
                monitor.Log($"Could not find a location with that name. Must be one of [{string.Join(", ", locationNames)}].", LogLevel.Error);
                return;
            }

            // apply
            switch (type)
            {
                case "crops":
                    {
                        int removed =
                            this.RemoveTerrainFeatures(location, p => p is HoeDirt)
                            + this.RemoveResourceClumps(location, p => p is GiantCrop);
                        monitor.Log($"Done! Removed {removed} entities from {location.Name}.", LogLevel.Info);
                        break;
                    }

                case "debris":
                    {
                        int removed = 0;
                        foreach (var pair in location.terrainFeatures.Pairs.ToArray())
                        {
                            TerrainFeature feature = pair.Value;
                            if (feature is HoeDirt dirt && dirt.crop?.dead == true)
                            {
                                dirt.crop = null;
                                removed++;
                            }
                        }

                        removed +=
                            this.RemoveObjects(location, obj =>
                                !(obj is Chest)
                                && (
                                    obj.Name == "Weeds"
                                    || obj.Name == "Stone"
                                    || (obj.ParentSheetIndex == 294 || obj.ParentSheetIndex == 295)
                                )
                            )
                            + this.RemoveResourceClumps(location, clump => this.DebrisClumps.Contains(clump.parentSheetIndex.Value));

                        monitor.Log($"Done! Removed {removed} entities from {location.Name}.", LogLevel.Info);
                        break;
                    }

                case "fruit-trees":
                    {
                        int removed = this.RemoveTerrainFeatures(location, feature => feature is FruitTree);
                        monitor.Log($"Done! Removed {removed} entities from {location.Name}.", LogLevel.Info);
                        break;
                    }

                case "furniture":
                    {
                        int removed = this.RemoveFurniture(location, furniture => true);
                        monitor.Log($"Done! Removed {removed} entities from {location.Name}.", LogLevel.Info);
                        break;
                    }

                case "grass":
                    {
                        int removed = this.RemoveTerrainFeatures(location, feature => feature is Grass);
                        monitor.Log($"Done! Removed {removed} entities from {location.Name}.", LogLevel.Info);
                        break;
                    }

                case "trees":
                    {
                        int removed = this.RemoveTerrainFeatures(location, feature => feature is Tree);
                        monitor.Log($"Done! Removed {removed} entities from {location.Name}.", LogLevel.Info);
                        break;
                    }

                case "removable":
                case "everything":
                    {
                        bool everything = type == "everything";
                        int removed =
                            this.RemoveFurniture(location, p => true)
                            + this.RemoveObjects(location, p => true)
                            + this.RemoveTerrainFeatures(location, p => true)
                            + this.RemoveLargeTerrainFeatures(location, p => everything || !(p is Bush bush) || bush.isDestroyable(location, p.currentTileLocation))
                            + this.RemoveResourceClumps(location, p => true);
                        monitor.Log($"Done! Removed {removed} entities from {location.Name}.", LogLevel.Info);
                        break;
                    }

                default:
                    monitor.Log($"Unknown type '{type}'. Must be one [{string.Join(", ", this.ValidTypes)}].", LogLevel.Error);
                    break;
            }
        }


        /*********
        ** Private methods
        *********/
        /// <summary>Remove objects from a location matching a lambda.</summary>
        /// <param name="location">The location to search.</param>
        /// <param name="shouldRemove">Whether an entity should be removed.</param>
        /// <returns>Returns the number of removed entities.</returns>
        private int RemoveObjects(GameLocation location, Func<SObject, bool> shouldRemove)
        {
            int removed = 0;

            foreach (var pair in location.Objects.Pairs.ToArray())
            {
                if (shouldRemove(pair.Value))
                {
                    location.Objects.Remove(pair.Key);
                    removed++;
                }
            }

            return removed;
        }

        /// <summary>Remove terrain features from a location matching a lambda.</summary>
        /// <param name="location">The location to search.</param>
        /// <param name="shouldRemove">Whether an entity should be removed.</param>
        /// <returns>Returns the number of removed entities.</returns>
        private int RemoveTerrainFeatures(GameLocation location, Func<TerrainFeature, bool> shouldRemove)
        {
            int removed = 0;

            foreach (var pair in location.terrainFeatures.Pairs.ToArray())
            {
                if (shouldRemove(pair.Value))
                {
                    location.terrainFeatures.Remove(pair.Key);
                    removed++;
                }
            }

            return removed;
        }

        /// <summary>Remove large terrain features from a location matching a lambda.</summary>
        /// <param name="location">The location to search.</param>
        /// <param name="shouldRemove">Whether an entity should be removed.</param>
        /// <returns>Returns the number of removed entities.</returns>
        private int RemoveLargeTerrainFeatures(GameLocation location, Func<LargeTerrainFeature, bool> shouldRemove)
        {
            int removed = 0;

            foreach (LargeTerrainFeature feature in location.largeTerrainFeatures.ToArray())
            {
                if (shouldRemove(feature))
                {
                    location.largeTerrainFeatures.Remove(feature);
                    removed++;
                }
            }

            return removed;
        }

        /// <summary>Remove resource clumps from a location matching a lambda.</summary>
        /// <param name="location">The location to search.</param>
        /// <param name="shouldRemove">Whether an entity should be removed.</param>
        /// <returns>Returns the number of removed entities.</returns>
        private int RemoveResourceClumps(GameLocation location, Func<ResourceClump, bool> shouldRemove)
        {
            int removed = 0;

            foreach (var clump in location.resourceClumps.Where(shouldRemove).ToArray())
            {
                location.resourceClumps.Remove(clump);
                removed++;
            }

            if (location is Woods woods)
            {
                foreach (ResourceClump clump in woods.stumps.Where(shouldRemove).ToArray())
                {
                    woods.stumps.Remove(clump);
                    removed++;
                }
            }

            return removed;
        }

        /// <summary>Remove furniture from a location matching a lambda.</summary>
        /// <param name="location">The location to search.</param>
        /// <param name="shouldRemove">Whether an entity should be removed.</param>
        /// <returns>Returns the number of removed entities.</returns>
        private int RemoveFurniture(GameLocation location, Func<Furniture, bool> shouldRemove)
        {
            int removed = 0;

            foreach (Furniture furniture in location.furniture.ToArray())
            {
                if (shouldRemove(furniture))
                {
                    location.furniture.Remove(furniture);
                    removed++;
                }
            }

            return removed;
        }
    }
}