-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMapRestrictions.cs
More file actions
286 lines (233 loc) · 8.88 KB
/
Copy pathMapRestrictions.cs
File metadata and controls
286 lines (233 loc) · 8.88 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
using System.Text.Json;
using CounterStrikeSharp.API.Core;
using CounterStrikeSharp.API.Core.Attributes.Registration;
using CounterStrikeSharp.API.Modules.Utils;
using CounterStrikeSharp.API;
using CounterStrikeSharp.API.Modules.Admin;
using CounterStrikeSharp.API.Modules.Commands;
namespace MapRestrictions;
public class MapRestrictions : BasePlugin
{
public override string ModuleAuthor => "NiGHT";
public override string ModuleName => "MapRestrictions";
public override string ModuleDescription => "Restrict maps to certain players";
public override string ModuleVersion => "0.0.2";
public class MapData
{
public string? MapName { get; set; }
public MapRestriction Restrictions { get; set; } = new();
}
public class MapRestriction
{
public string Model { get; set; } = string.Empty;
public bool UpdateOnPlayerConnect { get; set; } = false;
public bool CountBots { get; set; } = false;
public Dictionary<string, MapMessages> Messages { get; set; } = new();
public Dictionary<string, MapArea> Areas { get; set; } = new();
}
public class MapMessages
{
public int LessThan { get; set; }
public int MoreThan { get; set; }
public string? Message { get; set; }
}
public class MapArea
{
public int LessThan { get; set; }
public int MoreThan { get; set; }
public string? Origin { get; set; }
public string? Angles { get; set; }
public string? Scale { get; set; }
}
private string? _msg;
private string? _path;
private CCSGameRules? _gameRules;
private MapData? _mapData;
private readonly HashSet<CBaseModelEntity> _spawnedProps = new();
private void LoadConfig(string name)
{
if (_mapData != null)
{
_mapData.Restrictions.Areas.Clear();
_mapData.Restrictions.Messages.Clear();
_mapData.Restrictions.Model = string.Empty;
_mapData = null;
}
_path = ModuleDirectory + "/configs/" + name + ".json";
Console.WriteLine($"{ModuleName} LoadConfig - Loading map data from {_path}");
if (!File.Exists(_path))
{
Console.WriteLine($"{ModuleName} LoadConfig - No map data found for {_path}");
return;
}
Console.WriteLine($"{ModuleName} LoadConfig - Found map data for {_path}");
try
{
_mapData = JsonSerializer.Deserialize<MapData>(File.ReadAllText(_path));
}
catch (Exception ex)
{
// Handle any potential JSON parsing exceptions
Console.WriteLine($"{ModuleName} LoadConfig - Error loading map data: {ex.Message}");
}
}
public override void Load(bool hotReload)
{
RegisterListener<Listeners.OnMapStart>(LoadConfig);
if (!hotReload || _mapData != null)
return;
var name = Server.MapName;
if(string.IsNullOrEmpty(name))
return;
try
{
LoadConfig(name);
}
catch (Exception ex)
{
Console.WriteLine($"{ModuleName} Load - Error loading map data: {ex.Message}");
}
}
public override void Unload(bool hotReload)
{
ClearMapProps();
}
[GameEventHandler]
public HookResult OnRoundStart(EventRoundStart @event, GameEventInfo info)
{
if (_mapData == null)
return HookResult.Continue;
_spawnedProps.Clear();
_gameRules = GetGameRules();
SpawnProps();
return HookResult.Continue;
}
[GameEventHandler]
public HookResult OnPlayerConnect(EventPlayerConnect @event, GameEventInfo info)
{
CheckCounter();
return HookResult.Continue;
}
[GameEventHandler]
public HookResult OnPlayerDisconnect(EventPlayerDisconnect @event, GameEventInfo info)
{
CheckCounter();
return HookResult.Continue;
}
[ConsoleCommand("maprestrictions_reload")]
[RequiresPermissions("@css/root")]
[CommandHelper(whoCanExecute: CommandUsage.CLIENT_AND_SERVER)]
public void ReloadMapRestrictions(CCSPlayerController? caller, CommandInfo command)
{
ClearMapProps();
if (_path == null)
return;
try
{
_mapData = JsonSerializer.Deserialize<MapData>(File.ReadAllText(_path));
}
catch (Exception ex)
{
// Handle any potential JSON parsing exceptions
Console.WriteLine($"{ModuleName} ReloadMapRestrictions - Error loading map data: {ex.Message}");
}
var newRestrictionsCount = _mapData?.Restrictions.Areas.Count;
var newMessagesCount = _mapData?.Restrictions.Messages.Count;
if(caller == null)
Server.PrintToConsole($"[{ModuleName}] Reloaded map restrictions for {_mapData?.MapName}, found {newRestrictionsCount} restrictions and {newMessagesCount} messages");
else
caller.PrintToChat($"MapRestrictions - Reloaded map restrictions for {_mapData?.MapName}, found {newRestrictionsCount} restrictions and {newMessagesCount} messages");
SpawnProps();
}
private static CCSGameRules GetGameRules()
{
return Utilities.FindAllEntitiesByDesignerName<CCSGameRulesProxy>("cs_gamerules").First().GameRules!;
}
private static Vector StringToVector(string vector)
{
var split = vector.Split(' ');
return new Vector(float.Parse(split[0]), float.Parse(split[1]), float.Parse(split[2]));
}
private static QAngle StringToQAngle(string vector)
{
var split = vector.Split(' ');
return new QAngle(float.Parse(split[0]), float.Parse(split[1]), float.Parse(split[2]));
}
private void SpawnProp(string modelPath, Vector origin, QAngle angles, float scale = 0.0f)
{
var prop = Utilities.CreateEntityByName<CBaseModelEntity>("prop_dynamic_override");
if (prop == null)
return;
prop.Collision.SolidType = SolidType_t.SOLID_VPHYSICS;
prop.Teleport(origin, angles, new Vector(0, 0, 0));
prop.DispatchSpawn();
Server.NextFrame(() => prop.SetModel(modelPath));
_spawnedProps.Add(prop);
if(scale == 0.0f)
return;
var bodyComponent = prop.CBodyComponent;
if (bodyComponent is not { SceneNode: not null })
return;
bodyComponent.SceneNode.GetSkeletonInstance().Scale = scale;
}
private void SpawnProps()
{
if(_mapData == null || _gameRules == null || _gameRules.WarmupPeriod)
return;
var players = Utilities.GetPlayers()
.Where(x => x.Connected == PlayerConnectedState.PlayerConnected
&& (!_mapData.Restrictions.CountBots || !x.IsBot))
.ToList();
var playersConnected = players.Count;
var message = GetMapMessage(playersConnected);
_msg = message;
// find the message to send
if (!string.IsNullOrEmpty(message))
{
// count ct and t players
var ctPlayers = players.Where(x => x is { Team: CsTeam.CounterTerrorist}).ToList().Count;
var tPlayers = players.Where(x => x is { Team: CsTeam.Terrorist}).ToList().Count;
Server.PrintToChatAll(Localizer["StartMessage"].Value.Replace("{tPlayers}", tPlayers.ToString()).Replace("{ctPlayers}", ctPlayers.ToString()).Replace("{message}", message));
}
// now let's spawn the props based on
var model = _mapData.Restrictions.Model;
for (var i = 0; i < _mapData.Restrictions.Areas.Count; i++)
{
var mapArea = _mapData.Restrictions.Areas.ElementAt(i).Value;
if (playersConnected > mapArea.MoreThan && (mapArea.LessThan == 0 || playersConnected < mapArea.LessThan))
{
if(mapArea is { Origin: not null, Angles: not null })
SpawnProp(model, StringToVector(mapArea.Origin), StringToQAngle(mapArea.Angles), string.IsNullOrEmpty(mapArea.Scale) ? 0.0f : float.Parse(mapArea.Scale));
}
}
}
private void CheckCounter()
{
if(_mapData == null || !_mapData.Restrictions.UpdateOnPlayerConnect || _msg == GetMapMessage(Utilities.GetPlayers().Where(x => x.Connected == PlayerConnectedState.PlayerConnected
&& (!_mapData.Restrictions.CountBots || !x.IsBot)).ToList().Count))
return;
ClearMapProps();
SpawnProps();
}
private void ClearMapProps()
{
foreach (var index in _spawnedProps.OfType<CBaseModelEntity>().Where(index => index.IsValid))
index.Remove();
_spawnedProps.Clear();
}
private string GetMapMessage(int playersConnected)
{
if(_mapData == null)
return string.Empty;
var message = String.Empty;
for (var i = 0; i < _mapData.Restrictions.Messages.Count; i++)
{
var mapMessage = _mapData.Restrictions.Messages.ElementAt(i).Value;
if (playersConnected > mapMessage.MoreThan && (mapMessage.LessThan == 0 || playersConnected < mapMessage.LessThan))
{
message = mapMessage.Message;
}
}
return message ?? String.Empty;
}
}