1
0

DecalSystem.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608
  1. using System.Linq;
  2. using System.Numerics;
  3. using System.Threading.Tasks;
  4. using Content.Server.Administration.Logs;
  5. using Content.Server.Administration.Managers;
  6. using Content.Shared.Administration;
  7. using Content.Shared.Chunking;
  8. using Content.Shared.Database;
  9. using Content.Shared.Decals;
  10. using Content.Shared.Maps;
  11. using Microsoft.Extensions.ObjectPool;
  12. using Robust.Server.GameObjects;
  13. using Robust.Server.Player;
  14. using Robust.Shared;
  15. using Robust.Shared.Configuration;
  16. using Robust.Shared.Enums;
  17. using Robust.Shared.Map;
  18. using Robust.Shared.Map.Components;
  19. using Robust.Shared.Player;
  20. using Robust.Shared.Threading;
  21. using Robust.Shared.Timing;
  22. using Robust.Shared.Utility;
  23. using static Content.Shared.Decals.DecalGridComponent;
  24. using ChunkIndicesEnumerator = Robust.Shared.Map.Enumerators.ChunkIndicesEnumerator;
  25. namespace Content.Server.Decals
  26. {
  27. public sealed class DecalSystem : SharedDecalSystem
  28. {
  29. [Dependency] private readonly IPlayerManager _playerManager = default!;
  30. [Dependency] private readonly IAdminManager _adminManager = default!;
  31. [Dependency] private readonly ITileDefinitionManager _tileDefMan = default!;
  32. [Dependency] private readonly IParallelManager _parMan = default!;
  33. [Dependency] private readonly ChunkingSystem _chunking = default!;
  34. [Dependency] private readonly IConfigurationManager _conf = default!;
  35. [Dependency] private readonly IGameTiming _timing = default!;
  36. [Dependency] private readonly IAdminLogManager _adminLogger = default!;
  37. [Dependency] private readonly SharedMapSystem _mapSystem = default!;
  38. private readonly Dictionary<NetEntity, HashSet<Vector2i>> _dirtyChunks = new();
  39. private readonly Dictionary<ICommonSession, Dictionary<NetEntity, HashSet<Vector2i>>> _previousSentChunks = new();
  40. private static readonly Vector2 _boundsMinExpansion = new(0.01f, 0.01f);
  41. private static readonly Vector2 _boundsMaxExpansion = new(1.01f, 1.01f);
  42. private UpdatePlayerJob _updateJob;
  43. private List<ICommonSession> _sessions = new();
  44. // If this ever gets parallelised then you'll want to increase the pooled count.
  45. private ObjectPool<HashSet<Vector2i>> _chunkIndexPool =
  46. new DefaultObjectPool<HashSet<Vector2i>>(
  47. new DefaultPooledObjectPolicy<HashSet<Vector2i>>(), 64);
  48. private ObjectPool<Dictionary<NetEntity, HashSet<Vector2i>>> _chunkViewerPool =
  49. new DefaultObjectPool<Dictionary<NetEntity, HashSet<Vector2i>>>(
  50. new DefaultPooledObjectPolicy<Dictionary<NetEntity, HashSet<Vector2i>>>(), 64);
  51. public override void Initialize()
  52. {
  53. base.Initialize();
  54. _updateJob = new UpdatePlayerJob()
  55. {
  56. System = this,
  57. Sessions = _sessions,
  58. };
  59. _playerManager.PlayerStatusChanged += OnPlayerStatusChanged;
  60. SubscribeLocalEvent<TileChangedEvent>(OnTileChanged);
  61. SubscribeNetworkEvent<RequestDecalPlacementEvent>(OnDecalPlacementRequest);
  62. SubscribeNetworkEvent<RequestDecalRemovalEvent>(OnDecalRemovalRequest);
  63. SubscribeLocalEvent<PostGridSplitEvent>(OnGridSplit);
  64. Subs.CVar(_conf, CVars.NetPVS, OnPvsToggle, true);
  65. }
  66. private void OnPvsToggle(bool value)
  67. {
  68. if (value == PvsEnabled)
  69. return;
  70. PvsEnabled = value;
  71. if (value)
  72. return;
  73. foreach (var playerData in _previousSentChunks.Values)
  74. {
  75. playerData.Clear();
  76. }
  77. var query = AllEntityQuery<DecalGridComponent, MetaDataComponent>();
  78. while (query.MoveNext(out var uid, out var grid, out var meta))
  79. {
  80. grid.ForceTick = _timing.CurTick;
  81. Dirty(uid, grid, meta);
  82. }
  83. }
  84. private void OnGridSplit(ref PostGridSplitEvent ev)
  85. {
  86. if (!TryComp(ev.OldGrid, out DecalGridComponent? oldComp))
  87. return;
  88. if (!TryComp(ev.Grid, out DecalGridComponent? newComp))
  89. return;
  90. // Transfer decals over to the new grid.
  91. var enumerator = _mapSystem.GetAllTilesEnumerator(ev.Grid, Comp<MapGridComponent>(ev.Grid));
  92. var oldChunkCollection = oldComp.ChunkCollection.ChunkCollection;
  93. var chunkCollection = newComp.ChunkCollection.ChunkCollection;
  94. while (enumerator.MoveNext(out var tile))
  95. {
  96. var tilePos = (Vector2) tile.Value.GridIndices;
  97. var chunkIndices = GetChunkIndices(tilePos);
  98. if (!oldChunkCollection.TryGetValue(chunkIndices, out var oldChunk))
  99. continue;
  100. var bounds = new Box2(tilePos - _boundsMinExpansion, tilePos + _boundsMaxExpansion);
  101. var toRemove = new RemQueue<uint>();
  102. foreach (var (oldDecalId, decal) in oldChunk.Decals)
  103. {
  104. if (!bounds.Contains(decal.Coordinates))
  105. continue;
  106. var newDecalId = newComp.ChunkCollection.NextDecalId++;
  107. var newChunk = chunkCollection.GetOrNew(chunkIndices);
  108. newChunk.Decals[newDecalId] = decal;
  109. newComp.DecalIndex[newDecalId] = chunkIndices;
  110. toRemove.Add(oldDecalId);
  111. }
  112. foreach (var oldDecalId in toRemove)
  113. {
  114. oldChunk.Decals.Remove(oldDecalId);
  115. oldComp.DecalIndex.Remove(oldDecalId);
  116. }
  117. DirtyChunk(ev.Grid, chunkIndices, chunkCollection.GetOrNew(chunkIndices));
  118. if (oldChunk.Decals.Count == 0)
  119. oldChunkCollection.Remove(chunkIndices);
  120. if (toRemove.List?.Count > 0)
  121. DirtyChunk(ev.OldGrid, chunkIndices, oldChunk);
  122. }
  123. }
  124. public override void Shutdown()
  125. {
  126. base.Shutdown();
  127. _playerManager.PlayerStatusChanged -= OnPlayerStatusChanged;
  128. }
  129. private void OnTileChanged(ref TileChangedEvent args)
  130. {
  131. if (!args.NewTile.IsSpace(_tileDefMan))
  132. return;
  133. if (!TryComp(args.Entity, out DecalGridComponent? grid))
  134. return;
  135. var indices = GetChunkIndices(args.NewTile.GridIndices);
  136. var toDelete = new HashSet<uint>();
  137. if (!grid.ChunkCollection.ChunkCollection.TryGetValue(indices, out var chunk))
  138. return;
  139. foreach (var (uid, decal) in chunk.Decals)
  140. {
  141. if (new Vector2((int) Math.Floor(decal.Coordinates.X), (int) Math.Floor(decal.Coordinates.Y)) ==
  142. args.NewTile.GridIndices)
  143. {
  144. toDelete.Add(uid);
  145. }
  146. }
  147. if (toDelete.Count == 0)
  148. return;
  149. foreach (var decalId in toDelete)
  150. {
  151. grid.DecalIndex.Remove(decalId);
  152. chunk.Decals.Remove(decalId);
  153. }
  154. DirtyChunk(args.Entity, indices, chunk);
  155. if (chunk.Decals.Count == 0)
  156. grid.ChunkCollection.ChunkCollection.Remove(indices);
  157. }
  158. private void OnPlayerStatusChanged(object? sender, SessionStatusEventArgs e)
  159. {
  160. switch (e.NewStatus)
  161. {
  162. case SessionStatus.InGame:
  163. _previousSentChunks[e.Session] = new();
  164. break;
  165. case SessionStatus.Disconnected:
  166. _previousSentChunks.Remove(e.Session);
  167. break;
  168. }
  169. }
  170. private void OnDecalPlacementRequest(RequestDecalPlacementEvent ev, EntitySessionEventArgs eventArgs)
  171. {
  172. if (eventArgs.SenderSession is not { } session)
  173. return;
  174. // bad
  175. if (!_adminManager.HasAdminFlag(session, AdminFlags.Spawn))
  176. return;
  177. var coordinates = GetCoordinates(ev.Coordinates);
  178. if (!coordinates.IsValid(EntityManager))
  179. return;
  180. if (!TryAddDecal(ev.Decal, coordinates, out _))
  181. return;
  182. if (eventArgs.SenderSession.AttachedEntity != null)
  183. {
  184. _adminLogger.Add(LogType.CrayonDraw, LogImpact.High,
  185. $"{ToPrettyString(eventArgs.SenderSession.AttachedEntity.Value):actor} drew a {ev.Decal.Color} {ev.Decal.Id} at {ev.Coordinates}");
  186. }
  187. else
  188. {
  189. _adminLogger.Add(LogType.CrayonDraw, LogImpact.High,
  190. $"{eventArgs.SenderSession.Name} drew a {ev.Decal.Color} {ev.Decal.Id} at {ev.Coordinates}");
  191. }
  192. }
  193. private void OnDecalRemovalRequest(RequestDecalRemovalEvent ev, EntitySessionEventArgs eventArgs)
  194. {
  195. if (eventArgs.SenderSession is not { } session)
  196. return;
  197. // bad
  198. if (!_adminManager.HasAdminFlag(session, AdminFlags.Spawn))
  199. return;
  200. var coordinates = GetCoordinates(ev.Coordinates);
  201. if (!coordinates.IsValid(EntityManager))
  202. return;
  203. var gridId = coordinates.GetGridUid(EntityManager);
  204. if (gridId == null)
  205. return;
  206. // remove all decals on the same tile
  207. foreach (var (decalId, decal) in GetDecalsInRange(gridId.Value, ev.Coordinates.Position))
  208. {
  209. if (eventArgs.SenderSession.AttachedEntity != null)
  210. {
  211. _adminLogger.Add(LogType.CrayonDraw, LogImpact.High,
  212. $"{ToPrettyString(eventArgs.SenderSession.AttachedEntity.Value):actor} removed a {decal.Color} {decal.Id} at {ev.Coordinates}");
  213. }
  214. else
  215. {
  216. _adminLogger.Add(LogType.CrayonDraw, LogImpact.High,
  217. $"{eventArgs.SenderSession.Name} removed a {decal.Color} {decal.Id} at {ev.Coordinates}");
  218. }
  219. RemoveDecal(gridId.Value, decalId);
  220. }
  221. }
  222. protected override void DirtyChunk(EntityUid uid, Vector2i chunkIndices, DecalChunk chunk)
  223. {
  224. var id = GetNetEntity(uid);
  225. chunk.LastModified = _timing.CurTick;
  226. if(!_dirtyChunks.ContainsKey(id))
  227. _dirtyChunks[id] = new HashSet<Vector2i>();
  228. _dirtyChunks[id].Add(chunkIndices);
  229. }
  230. public bool TryAddDecal(string id, EntityCoordinates coordinates, out uint decalId, Color? color = null, Angle? rotation = null, int zIndex = 0, bool cleanable = false)
  231. {
  232. rotation ??= Angle.Zero;
  233. var decal = new Decal(coordinates.Position, id, color, rotation.Value, zIndex, cleanable);
  234. return TryAddDecal(decal, coordinates, out decalId);
  235. }
  236. public bool TryAddDecal(Decal decal, EntityCoordinates coordinates, out uint decalId)
  237. {
  238. decalId = 0;
  239. if (!PrototypeManager.HasIndex<DecalPrototype>(decal.Id))
  240. return false;
  241. var gridId = coordinates.GetGridUid(EntityManager);
  242. if (!TryComp(gridId, out MapGridComponent? grid))
  243. return false;
  244. if (_mapSystem.GetTileRef(gridId.Value, grid, coordinates).IsSpace(_tileDefMan))
  245. return false;
  246. if (!TryComp(gridId, out DecalGridComponent? comp))
  247. return false;
  248. decalId = comp.ChunkCollection.NextDecalId++;
  249. var chunkIndices = GetChunkIndices(decal.Coordinates);
  250. var chunk = comp.ChunkCollection.ChunkCollection.GetOrNew(chunkIndices);
  251. chunk.Decals[decalId] = decal;
  252. comp.DecalIndex[decalId] = chunkIndices;
  253. DirtyChunk(gridId.Value, chunkIndices, chunk);
  254. return true;
  255. }
  256. public override bool RemoveDecal(EntityUid gridId, uint decalId, DecalGridComponent? component = null)
  257. => RemoveDecalInternal(gridId, decalId, out _, component);
  258. public override HashSet<(uint Index, Decal Decal)> GetDecalsInRange(EntityUid gridId, Vector2 position, float distance = 0.75f, Func<Decal, bool>? validDelegate = null)
  259. {
  260. var decalIds = new HashSet<(uint, Decal)>();
  261. var chunkCollection = ChunkCollection(gridId);
  262. var chunkIndices = GetChunkIndices(position);
  263. if (chunkCollection == null || !chunkCollection.TryGetValue(chunkIndices, out var chunk))
  264. return decalIds;
  265. foreach (var (uid, decal) in chunk.Decals)
  266. {
  267. if ((position - decal.Coordinates - new Vector2(0.5f, 0.5f)).Length() > distance)
  268. continue;
  269. if (validDelegate == null || validDelegate(decal))
  270. {
  271. decalIds.Add((uid, decal));
  272. }
  273. }
  274. return decalIds;
  275. }
  276. public HashSet<(uint Index, Decal Decal)> GetDecalsIntersecting(EntityUid gridUid, Box2 bounds, DecalGridComponent? component = null)
  277. {
  278. var decalIds = new HashSet<(uint, Decal)>();
  279. var chunkCollection = ChunkCollection(gridUid, component);
  280. if (chunkCollection == null)
  281. return decalIds;
  282. var chunks = new ChunkIndicesEnumerator(bounds, ChunkSize);
  283. while (chunks.MoveNext(out var chunkOrigin))
  284. {
  285. if (!chunkCollection.TryGetValue(chunkOrigin.Value, out var chunk))
  286. continue;
  287. foreach (var (id, decal) in chunk.Decals)
  288. {
  289. if (!bounds.Contains(decal.Coordinates))
  290. continue;
  291. decalIds.Add((id, decal));
  292. }
  293. }
  294. return decalIds;
  295. }
  296. /// <summary>
  297. /// Changes a decals position. Note this will actually result in a new decal being created, possibly on a new grid or chunk.
  298. /// </summary>
  299. /// <remarks>
  300. /// If the new position is invalid, this will result in the decal getting deleted.
  301. /// </remarks>
  302. public bool SetDecalPosition(EntityUid gridId, uint decalId, EntityCoordinates coordinates, DecalGridComponent? comp = null)
  303. {
  304. if (!Resolve(gridId, ref comp))
  305. return false;
  306. if (!RemoveDecalInternal(gridId, decalId, out var removed, comp))
  307. return false;
  308. return TryAddDecal(removed.WithCoordinates(coordinates.Position), coordinates, out _);
  309. }
  310. private bool ModifyDecal(EntityUid gridId, uint decalId, Func<Decal, Decal> modifyDecal, DecalGridComponent? comp = null)
  311. {
  312. if (!Resolve(gridId, ref comp))
  313. return false;
  314. if (!comp.DecalIndex.TryGetValue(decalId, out var indices))
  315. return false;
  316. var chunk = comp.ChunkCollection.ChunkCollection[indices];
  317. var decal = chunk.Decals[decalId];
  318. chunk.Decals[decalId] = modifyDecal(decal);
  319. DirtyChunk(gridId, indices, chunk);
  320. return true;
  321. }
  322. public bool SetDecalColor(EntityUid gridId, uint decalId, Color? value, DecalGridComponent? comp = null)
  323. => ModifyDecal(gridId, decalId, x => x.WithColor(value), comp);
  324. public bool SetDecalRotation(EntityUid gridId, uint decalId, Angle value, DecalGridComponent? comp = null)
  325. => ModifyDecal(gridId, decalId, x => x.WithRotation(value), comp);
  326. public bool SetDecalZIndex(EntityUid gridId, uint decalId, int value, DecalGridComponent? comp = null)
  327. => ModifyDecal(gridId, decalId, x => x.WithZIndex(value), comp);
  328. public bool SetDecalCleanable(EntityUid gridId, uint decalId, bool value, DecalGridComponent? comp = null)
  329. => ModifyDecal(gridId, decalId, x => x.WithCleanable(value), comp);
  330. public bool SetDecalId(EntityUid gridId, uint decalId, string id, DecalGridComponent? comp = null)
  331. {
  332. if (!PrototypeManager.HasIndex<DecalPrototype>(id))
  333. throw new ArgumentOutOfRangeException($"Tried to set decal id to invalid prototypeid: {id}");
  334. return ModifyDecal(gridId, decalId, x => x.WithId(id), comp);
  335. }
  336. public override void Update(float frameTime)
  337. {
  338. base.Update(frameTime);
  339. foreach (var ent in _dirtyChunks.Keys)
  340. {
  341. if (TryGetEntity(ent, out var uid) && TryComp(uid, out DecalGridComponent? decals))
  342. Dirty(uid.Value, decals);
  343. }
  344. if (!PvsEnabled)
  345. {
  346. _dirtyChunks.Clear();
  347. return;
  348. }
  349. if (PvsEnabled)
  350. {
  351. _sessions.Clear();
  352. foreach (var session in _playerManager.Sessions)
  353. {
  354. if (session.Status != SessionStatus.InGame)
  355. continue;
  356. _sessions.Add(session);
  357. }
  358. if (_sessions.Count > 0)
  359. _parMan.ProcessNow(_updateJob, _sessions.Count);
  360. }
  361. _dirtyChunks.Clear();
  362. }
  363. public void UpdatePlayer(ICommonSession player)
  364. {
  365. var chunksInRange = _chunking.GetChunksForSession(player, ChunkSize, _chunkIndexPool, _chunkViewerPool);
  366. var staleChunks = _chunkViewerPool.Get();
  367. var previouslySent = _previousSentChunks[player];
  368. // Get any chunks not in range anymore
  369. // Then, remove them from previousSentChunks (for stuff like grids out of range)
  370. // and also mark them as stale for networking.
  371. foreach (var (netGrid, oldIndices) in previouslySent)
  372. {
  373. // Mark the whole grid as stale and flag for removal.
  374. if (!chunksInRange.TryGetValue(netGrid, out var chunks))
  375. {
  376. previouslySent.Remove(netGrid);
  377. // Was the grid deleted?
  378. if (TryGetEntity(netGrid, out var gridId) && HasComp<MapGridComponent>(gridId.Value))
  379. {
  380. // no -> add it to the list of stale chunks
  381. staleChunks[netGrid] = oldIndices;
  382. }
  383. else
  384. {
  385. // If the grid was deleted then don't worry about telling the client to delete the chunk.
  386. oldIndices.Clear();
  387. _chunkIndexPool.Return(oldIndices);
  388. }
  389. continue;
  390. }
  391. var elmo = _chunkIndexPool.Get();
  392. // Get individual stale chunks.
  393. foreach (var chunk in oldIndices)
  394. {
  395. if (chunks.Contains(chunk))
  396. continue;
  397. elmo.Add(chunk);
  398. }
  399. if (elmo.Count == 0)
  400. {
  401. _chunkIndexPool.Return(elmo);
  402. continue;
  403. }
  404. staleChunks.Add(netGrid, elmo);
  405. }
  406. var updatedChunks = _chunkViewerPool.Get();
  407. foreach (var (netGrid, gridChunks) in chunksInRange)
  408. {
  409. var newChunks = _chunkIndexPool.Get();
  410. _dirtyChunks.TryGetValue(netGrid, out var dirtyChunks);
  411. if (!previouslySent.TryGetValue(netGrid, out var previousChunks))
  412. newChunks.UnionWith(gridChunks);
  413. else
  414. {
  415. foreach (var index in gridChunks)
  416. {
  417. if (!previousChunks.Contains(index) || dirtyChunks != null && dirtyChunks.Contains(index))
  418. newChunks.Add(index);
  419. }
  420. previousChunks.Clear();
  421. _chunkIndexPool.Return(previousChunks);
  422. }
  423. previouslySent[netGrid] = gridChunks;
  424. if (newChunks.Count == 0)
  425. _chunkIndexPool.Return(newChunks);
  426. else
  427. updatedChunks[netGrid] = newChunks;
  428. }
  429. //send all gridChunks to client
  430. SendChunkUpdates(player, updatedChunks, staleChunks);
  431. }
  432. private void ReturnToPool(Dictionary<NetEntity, HashSet<Vector2i>> chunks)
  433. {
  434. foreach (var (_, previous) in chunks)
  435. {
  436. previous.Clear();
  437. _chunkIndexPool.Return(previous);
  438. }
  439. chunks.Clear();
  440. _chunkViewerPool.Return(chunks);
  441. }
  442. private void SendChunkUpdates(
  443. ICommonSession session,
  444. Dictionary<NetEntity, HashSet<Vector2i>> updatedChunks,
  445. Dictionary<NetEntity, HashSet<Vector2i>> staleChunks)
  446. {
  447. var updatedDecals = new Dictionary<NetEntity, Dictionary<Vector2i, DecalChunk>>();
  448. foreach (var (netGrid, chunks) in updatedChunks)
  449. {
  450. var gridId = GetEntity(netGrid);
  451. var collection = ChunkCollection(gridId);
  452. if (collection == null)
  453. continue;
  454. var gridChunks = new Dictionary<Vector2i, DecalChunk>();
  455. foreach (var indices in chunks)
  456. {
  457. gridChunks.Add(indices,
  458. collection.TryGetValue(indices, out var chunk)
  459. ? chunk
  460. : new());
  461. }
  462. updatedDecals[netGrid] = gridChunks;
  463. }
  464. if (updatedDecals.Count != 0 || staleChunks.Count != 0)
  465. RaiseNetworkEvent(new DecalChunkUpdateEvent{Data = updatedDecals, RemovedChunks = staleChunks}, session);
  466. ReturnToPool(updatedChunks);
  467. ReturnToPool(staleChunks);
  468. }
  469. #region Jobs
  470. /// <summary>
  471. /// Updates per-player data for decals.
  472. /// </summary>
  473. private record struct UpdatePlayerJob : IParallelRobustJob
  474. {
  475. public int BatchSize => 2;
  476. public DecalSystem System;
  477. public List<ICommonSession> Sessions;
  478. public void Execute(int index)
  479. {
  480. System.UpdatePlayer(Sessions[index]);
  481. }
  482. }
  483. #endregion
  484. }
  485. }