forked from space-wizards/RobustToolbox
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDebug.cs
More file actions
968 lines (788 loc) · 32.3 KB
/
Copy pathDebug.cs
File metadata and controls
968 lines (788 loc) · 32.3 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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime;
using System.Text;
using System.Text.RegularExpressions;
using Robust.Client.Debugging;
using Robust.Client.Graphics;
using Robust.Client.Input;
using Robust.Client.ResourceManagement;
using Robust.Client.UserInterface;
using Robust.Client.UserInterface.Controls;
using Robust.Client.UserInterface.CustomControls;
using Robust.Shared.Asynchronous;
using Robust.Shared.Audio;
using Robust.Shared.Console;
using Robust.Shared.ContentPack;
using Robust.Shared.GameObjects;
using Robust.Shared.IoC;
using Robust.Shared.Localization;
using Robust.Shared.Map;
using Robust.Shared.Map.Components;
using Robust.Shared.Maths;
using Robust.Shared.Network;
using Robust.Shared.Reflection;
using Robust.Shared.Serialization;
using Robust.Shared.Utility;
using Robust.Shared.ViewVariables;
using static Robust.Client.UserInterface.Controls.BoxContainer;
namespace Robust.Client.Console.Commands
{
internal sealed partial class DumpEntitiesCommand : LocalizedCommands
{
[Dependency] private IEntityManager _entityManager = default!;
public override string Command => "dumpentities";
public override void Execute(IConsoleShell shell, string argStr, string[] args)
{
foreach (var e in _entityManager.GetEntities().OrderBy(e => e))
{
shell.WriteLine(
$"entity {e}, {_entityManager.GetComponent<MetaDataComponent>(e).EntityPrototype?.ID}, {_entityManager.GetComponent<TransformComponent>(e).Coordinates}.");
}
}
}
internal sealed partial class GetComponentRegistrationCommand : LocalizedCommands
{
[Dependency] private IComponentFactory _componentFactory = default!;
public override string Command => "getcomponentregistration";
public override void Execute(IConsoleShell shell, string argStr, string[] args)
{
if (args.Length < 1)
{
shell.WriteLine(Help);
return;
}
try
{
var registration = _componentFactory.GetRegistration(args[0]);
var message = new StringBuilder($"'{registration.Name}': (type: {registration.Type}, ");
if (registration.NetID == null)
{
message.Append("no Net ID");
}
else
{
message.Append($"net ID: {registration.NetID}");
}
shell.WriteLine(message.ToString());
}
catch (UnknownComponentException)
{
shell.WriteError($"No registration found for '{args[0]}'");
}
}
}
internal sealed partial class ToggleMonitorCommand : LocalizedCommands
{
[Dependency] private IUserInterfaceManager _uiMgr = default!;
public override string Command => "monitor";
public override string Help
{
get
{
var monitors = string.Join(", ", Enum.GetNames<DebugMonitor>());
return Loc.GetString("cmd-monitor-help", ("monitors", monitors));
}
}
public override void Execute(IConsoleShell shell, string argStr, string[] args)
{
var monitors = _uiMgr.DebugMonitors;
if (args.Length != 1)
{
shell.WriteLine(Loc.GetString("cmd-monitor-arg-count"));
return;
}
var monitorArg = args[0];
if (monitorArg.Equals("-all", StringComparison.OrdinalIgnoreCase))
{
foreach (var monitor in Enum.GetValues<DebugMonitor>())
{
monitors.SetMonitor(monitor, false);
}
return;
}
if (monitorArg.Equals("+all", StringComparison.OrdinalIgnoreCase))
{
foreach (var monitor in Enum.GetValues<DebugMonitor>())
{
monitors.SetMonitor(monitor, true);
}
return;
}
if (!Enum.TryParse(monitorArg, true, out DebugMonitor parsedMonitor))
{
shell.WriteError(Loc.GetString("cmd-monitor-invalid-name"));
return;
}
monitors.ToggleMonitor(parsedMonitor);
}
public override CompletionResult GetCompletion(IConsoleShell shell, string[] args)
{
if (args.Length == 1)
{
var allOptions = new CompletionOption[]
{
new("-all", Loc.GetString("cmd-monitor-minus-all-hint")),
new("+all", Loc.GetString("cmd-monitor-plus-all-hint"))
};
var options = allOptions.Concat(Enum.GetNames<DebugMonitor>().Select(c => new CompletionOption(c)));
return CompletionResult.FromHintOptions(options, Loc.GetString("cmd-monitor-arg-monitor"));
}
return CompletionResult.Empty;
}
}
internal sealed class ExceptionCommand : LocalizedCommands
{
public override string Command => "fuck";
public override void Execute(IConsoleShell shell, string argStr, string[] args)
{
throw new InvalidOperationException("Fuck");
}
}
internal sealed partial class ShowPositionsCommand : LocalizedEntityCommands
{
[Dependency] private DebugDrawingSystem _debugDrawing = default!;
public override string Command => "showpos";
public override void Execute(IConsoleShell shell, string argStr, string[] args)
{
_debugDrawing.DebugPositions = !_debugDrawing.DebugPositions;
}
}
internal sealed partial class ShowRotationsCommand : LocalizedEntityCommands
{
[Dependency] private DebugDrawingSystem _debugDrawing = default!;
public override string Command => "showrot";
public override void Execute(IConsoleShell shell, string argStr, string[] args)
{
_debugDrawing.DebugRotations = !_debugDrawing.DebugRotations;
}
}
internal sealed partial class ShowVelocitiesCommand : LocalizedEntityCommands
{
[Dependency] private DebugDrawingSystem _debugDrawing = default!;
public override string Command => "showvel";
public override void Execute(IConsoleShell shell, string argStr, string[] args)
{
_debugDrawing.DebugVelocities = !_debugDrawing.DebugVelocities;
}
}
internal sealed partial class ShowAngularVelocitiesCommand : LocalizedEntityCommands
{
[Dependency] private DebugDrawingSystem _debugDrawing = default!;
public override string Command => "showangvel";
public override void Execute(IConsoleShell shell, string argStr, string[] args)
{
_debugDrawing.DebugAngularVelocities = !_debugDrawing.DebugAngularVelocities;
}
}
#if DEBUG
internal sealed partial class ShowRayCommand : LocalizedCommands
{
[Dependency] private IEntitySystemManager _entitySystems = default!;
public override string Command => "showrays";
public override void Execute(IConsoleShell shell, string argStr, string[] args)
{
if (args.Length != 1)
{
shell.WriteLine(Help);
return;
}
if (!float.TryParse(args[0], out var duration))
{
shell.WriteError($"{args[0]} is not a valid float.");
return;
}
var mgr = _entitySystems.GetEntitySystem<DebugRayDrawingSystem>();
mgr.DebugDrawRays = !mgr.DebugDrawRays;
shell.WriteError("Toggled showing rays to:" + mgr.DebugDrawRays);
mgr.DebugRayLifetime = TimeSpan.FromSeconds(duration);
}
}
#endif
internal sealed partial class DisconnectCommand : LocalizedCommands
{
[Dependency] private IClientNetManager _netManager = default!;
public override string Command => "disconnect";
public override void Execute(IConsoleShell shell, string argStr, string[] args)
{
_netManager.ClientDisconnect("Disconnect command used.");
}
}
internal sealed partial class EntityInfoCommand : LocalizedCommands
{
[Dependency] private IEntityManager _entityManager = default!;
public override string Command => "entfo";
public override void Execute(IConsoleShell shell, string argStr, string[] args)
{
if (args.Length != 1)
{
shell.WriteLine(Help);
return;
}
if ((!new Regex(@"^c?[0-9]+$").IsMatch(args[0])))
{
shell.WriteError("Malformed UID");
return;
}
var uid = EntityUid.Parse(args[0]);
var entmgr = _entityManager;
if (!entmgr.EntityExists(uid))
{
shell.WriteError("That entity does not exist. Sorry lad.");
return;
}
var meta = entmgr.GetComponent<MetaDataComponent>(uid);
shell.WriteLine($"{uid}: {meta.EntityPrototype?.ID}/{meta.EntityName}");
shell.WriteLine(
$"init/del/lmt: {meta.EntityInitialized}/{meta.EntityDeleted}/{meta.EntityLastModifiedTick}");
foreach (var component in entmgr.GetComponents(uid))
{
shell.WriteLine(component.ToString() ?? "");
if (component is IComponentDebug debug)
{
foreach (var line in debug.GetDebugString().Split('\n'))
{
if (string.IsNullOrWhiteSpace(line))
{
continue;
}
shell.WriteLine("\t" + line);
}
}
}
}
}
internal sealed partial class SnapGridGetCell : LocalizedEntityCommands
{
[Dependency] private SharedMapSystem _map = default!;
public override string Command => "sggcell";
public override void Execute(IConsoleShell shell, string argStr, string[] args)
{
if (args.Length != 2)
{
shell.WriteLine(Help);
return;
}
string indices = args[1];
if (!NetEntity.TryParse(args[0], out var gridNet))
{
shell.WriteError($"{args[0]} is not a valid entity UID.");
return;
}
if (!new Regex(@"^-?[0-9]+,-?[0-9]+$").IsMatch(indices))
{
shell.WriteError("mapIndicies must be of form x<int>,y<int>");
return;
}
var gridEnt = EntityManager.GetEntity(gridNet);
if (EntityManager.TryGetComponent<MapGridComponent>(gridEnt, out var grid))
{
foreach (var entity in _map.GetAnchoredEntities(gridEnt, grid, new Vector2i(
int.Parse(indices.Split(',')[0], CultureInfo.InvariantCulture),
int.Parse(indices.Split(',')[1], CultureInfo.InvariantCulture))))
{
shell.WriteLine(entity.ToString());
}
}
else
{
shell.WriteError("grid does not exist");
}
}
}
internal sealed partial class SetPlayerName : LocalizedCommands
{
[Dependency] private IBaseClient _baseClient = default!;
public override string Command => "overrideplayername";
public override void Execute(IConsoleShell shell, string argStr, string[] args)
{
if (args.Length < 1)
{
shell.WriteLine(Help);
return;
}
_baseClient.PlayerNameOverride = args[0];
shell.WriteLine($"Overriding player name to \"{args[0]}\".");
}
}
internal sealed partial class LoadResource : LocalizedCommands
{
[Dependency] private IResourceCache _res = default!;
[Dependency] private IReflectionManager _reflection = default!;
public override string Command => "ldrsc";
public override void Execute(IConsoleShell shell, string argStr, string[] args)
{
if (args.Length < 2)
{
shell.WriteLine(Help);
return;
}
Type type;
try
{
type = _reflection.LooseGetType(args[1]);
}
catch (ArgumentException)
{
shell.WriteError("Unable to find type");
return;
}
var getResourceMethod =
_res
.GetType()
.GetMethod("GetResource", new[] { typeof(string), typeof(bool) });
DebugTools.Assert(getResourceMethod != null);
var generic = getResourceMethod!.MakeGenericMethod(type);
generic.Invoke(_res, new object[] { args[0], true });
}
}
internal sealed partial class ReloadResource : LocalizedCommands
{
[Dependency] private IResourceCache _res = default!;
[Dependency] private IReflectionManager _reflection = default!;
public override string Command => "rldrsc";
public override void Execute(IConsoleShell shell, string argStr, string[] args)
{
if (args.Length < 2)
{
shell.WriteLine(Help);
return;
}
Type type;
try
{
type = _reflection.LooseGetType(args[1]);
}
catch (ArgumentException)
{
shell.WriteError("Unable to find type");
return;
}
var getResourceMethod = _res.GetType().GetMethod("ReloadResource", new[] { typeof(string) });
DebugTools.Assert(getResourceMethod != null);
var generic = getResourceMethod!.MakeGenericMethod(type);
generic.Invoke(_res, new object[] { args[0] });
}
}
internal sealed partial class GridTileCount : LocalizedEntityCommands
{
[Dependency] private SharedMapSystem _map = default!;
public override string Command => "gridtc";
public override void Execute(IConsoleShell shell, string argStr, string[] args)
{
if (args.Length != 1)
{
shell.WriteLine(Help);
return;
}
if (!NetEntity.TryParse(args[0], out var gridUidNet) ||
!EntityManager.TryGetEntity(gridUidNet, out var gridUid))
{
shell.WriteLine($"{args[0]} is not a valid entity UID.");
return;
}
if (EntityManager.TryGetComponent<MapGridComponent>(gridUid, out var grid))
{
shell.WriteLine(_map.GetAllTiles(gridUid.Value, grid).Count().ToString());
}
else
{
shell.WriteError($"No grid exists with id {gridUid}");
}
}
}
internal sealed partial class GuiDumpCommand : LocalizedCommands
{
[Dependency] private IUserInterfaceManager _ui = default!;
[Dependency] private IResourceManager _resManager = default!;
public override string Command => "guidump";
public override void Execute(IConsoleShell shell, string argStr, string[] args)
{
using var writer = _resManager.UserData.OpenWriteText(new ResPath("/guidump.txt"));
foreach (var root in _ui.AllRoots)
{
writer.WriteLine($"ROOT: {root}");
_writeNode(root, 0, writer);
writer.WriteLine("---------------");
}
shell.WriteLine("Saved guidump");
}
private static void _writeNode(Control control, int indents, TextWriter writer)
{
var indentation = new string(' ', indents * 2);
writer.WriteLine("{0}{1}", indentation, control);
foreach (var (key, value) in PropertyValuesFor(control))
{
writer.WriteLine("{2} * {0}: {1}", key, value, indentation);
}
foreach (var child in control.Children)
{
_writeNode(child, indents + 1, writer);
}
}
internal static List<MemberInfo> GetAllMembers(Control control)
{
var members = new List<MemberInfo>();
var type = control.GetType();
foreach (var fieldInfo in type.GetAllFields())
{
if (!ViewVariablesUtility.TryGetViewVariablesAccess(fieldInfo, out _))
{
continue;
}
members.Add(fieldInfo);
}
foreach (var propertyInfo in type.GetAllProperties())
{
if (!ViewVariablesUtility.TryGetViewVariablesAccess(propertyInfo, out _))
{
continue;
}
members.Add(propertyInfo);
}
return members;
}
internal static List<(string, string)> PropertyValuesFor(Control control)
{
var members = new List<(string, string)>();
foreach (var fieldInfo in GetAllMembers(control))
{
members.Add((fieldInfo.Name, fieldInfo.GetValue(control)?.ToString() ?? "null"));
}
foreach (var (attachedProperty, value) in control.AllAttachedProperties)
{
members.Add(($"{attachedProperty.OwningType.Name}.{attachedProperty.Name}",
value?.ToString() ?? "null"));
}
members.Sort((a, b) => string.Compare(a.Item1, b.Item1, StringComparison.Ordinal));
return members;
}
internal static Dictionary<string, List<(string, string)>> PropertyValuesForInheritance(Control control)
{
var returnVal = new Dictionary<string, List<(string, string)>>();
var engine = typeof(Control).Assembly;
foreach (var member in GetAllMembers(control))
{
var type = member.DeclaringType!;
var cname = type.Assembly == engine ? type.Name : type.ToString();
if (type != typeof(Control))
cname = $"Control > {cname}";
returnVal.GetOrNew(cname).Add((member.Name, GetMemberValue(member, control, ", ")));
}
foreach (var (attachedProperty, value) in control.AllAttachedProperties)
{
var cname = $"Attached > {attachedProperty.OwningType.Name}";
returnVal.GetOrNew(cname).Add((attachedProperty.Name, value?.ToString() ?? "null"));
}
foreach (var v in returnVal.Values)
{
v.Sort((a, b) => string.Compare(a.Item1, b.Item1, StringComparison.Ordinal));
}
return returnVal;
}
internal static string PropertyValuesString(Control control, string key)
{
var member = GetAllMembers(control).Find(m => m.Name == key);
return GetMemberValue(member, control, "\n", "\"{0}\"");
}
private static string GetMemberValue(MemberInfo? member, Control control, string separator, string
wrap = "{0}")
{
object? value = null;
try
{
value = member?.GetValue(control);
}
catch (TargetInvocationException exception)
{
var exceptionToPrint = exception.InnerException ?? exception;
value = $"{exceptionToPrint.GetType()}: {exceptionToPrint.Message}";
}
catch (Exception exception)
{
value = $"{exception.GetType()}: {exception.Message}";
}
var o = value switch
{
ICollection<Control> controls => string.Join(separator,
controls.Select(ctrl => $"{ctrl.Name}({ctrl.GetType()})")),
ICollection<string> list => string.Join(separator, list),
null => null,
_ => value.ToString()
};
// Convert to quote surrounded string or null with no quotes
return o is not null ? string.Format(wrap, o) : "null";
}
}
internal sealed partial class SetClipboardCommand : LocalizedCommands
{
[Dependency] private IClipboardManager _clipboard = default!;
public override string Command => "setclipboard";
public override void Execute(IConsoleShell shell, string argStr, string[] args)
{
_clipboard.SetText(args[0]);
}
}
internal sealed partial class GetClipboardCommand : LocalizedCommands
{
[Dependency] private IClipboardManager _clipboard = default!;
public override string Command => "getclipboard";
public override async void Execute(IConsoleShell shell, string argStr, string[] args)
{
shell.WriteLine(await _clipboard.GetText());
}
}
internal sealed partial class ToggleLight : LocalizedCommands
{
[Dependency] private ILightManager _light = default!;
public override string Command => "togglelight";
public override void Execute(IConsoleShell shell, string argStr, string[] args)
{
if (!_light.LockConsoleAccess)
_light.Enabled = !_light.Enabled;
}
}
internal sealed partial class ToggleFOV : LocalizedCommands
{
[Dependency] private IEyeManager _eye = default!;
public override string Command => "togglefov";
public override void Execute(IConsoleShell shell, string argStr, string[] args)
{
_eye.CurrentEye.DrawFov = !_eye.CurrentEye.DrawFov;
}
}
internal sealed partial class ToggleHardFOV : LocalizedCommands
{
[Dependency] private ILightManager _light = default!;
public override string Command => "togglehardfov";
public override void Execute(IConsoleShell shell, string argStr, string[] args)
{
if (!_light.LockConsoleAccess)
_light.DrawHardFov = !_light.DrawHardFov;
}
}
internal sealed partial class ToggleShadows : LocalizedCommands
{
[Dependency] private ILightManager _light = default!;
public override string Command => "toggleshadows";
public override void Execute(IConsoleShell shell, string argStr, string[] args)
{
if (!_light.LockConsoleAccess)
_light.DrawShadows = !_light.DrawShadows;
}
}
internal sealed partial class ToggleLightBuf : LocalizedCommands
{
[Dependency] private ILightManager _light = default!;
public override string Command => "togglelightbuf";
public override void Execute(IConsoleShell shell, string argStr, string[] args)
{
if (!_light.LockConsoleAccess)
_light.DrawLighting = !_light.DrawLighting;
}
}
internal sealed partial class ChunkInfoCommand : LocalizedEntityCommands
{
[Dependency] private IEyeManager _eye = default!;
[Dependency] private IInputManager _input = default!;
[Dependency] private SharedMapSystem _mapSystem = default!;
public override string Command => "chunkinfo";
public override void Execute(IConsoleShell shell, string argStr, string[] args)
{
var mousePos = _eye.PixelToMap(_input.MouseScreenPosition);
if (!_mapSystem.TryFindGridAt(mousePos, out var gridUid, out var grid))
{
shell.WriteLine("No grid under your mouse cursor.");
return;
}
var mapSystem = EntityManager.System<SharedMapSystem>();
var chunkIndex = mapSystem.LocalToChunkIndices(gridUid, grid, _mapSystem.MapToGrid(gridUid, mousePos));
var chunk = mapSystem.GetOrAddChunk(gridUid, grid, chunkIndex);
shell.WriteLine($"worldBounds: {mapSystem.CalcWorldAABB(gridUid, grid, chunk)} localBounds: {chunk.CachedBounds}");
}
}
internal sealed partial class ReloadShadersCommand : LocalizedCommands
{
[Dependency] private IResourceCache _cache = default!;
[Dependency] private IResourceManagerInternal _resManager = default!;
[Dependency] private ITaskManager _taskManager = default!;
public override string Command => "rldshader";
public static Dictionary<string, FileSystemWatcher>? _watchers;
public static ConcurrentDictionary<string, bool>? _reloadShadersQueued = new();
public override void Execute(IConsoleShell shell, string argStr, string[] args)
{
var resC = _resManager;
if (args.Length == 1)
{
if (args[0] == "+watch")
{
if (_watchers != null)
{
shell.WriteLine("Already watching.");
return;
}
_watchers = new Dictionary<string, FileSystemWatcher>();
var stringComparer = PathHelpers.IsFileSystemCaseSensitive()
? StringComparer.Ordinal
: StringComparer.OrdinalIgnoreCase;
var reversePathResolution = new ConcurrentDictionary<string, HashSet<ResPath>>(stringComparer);
var taskManager = _taskManager;
var shaderCount = 0;
var created = 0;
var dirs = new ConcurrentDictionary<string, SortedSet<string>>(stringComparer);
foreach (var (path, src) in _cache.GetAllResources<ShaderSourceResource>())
{
if (!_resManager.TryGetDiskFilePath(path, out var fullPath))
{
throw new NotImplementedException();
}
reversePathResolution.GetOrAdd(fullPath, _ => new HashSet<ResPath>()).Add(path);
var dir = Path.GetDirectoryName(fullPath)!;
var fileName = Path.GetFileName(fullPath);
dirs.GetOrAdd(dir, _ => new SortedSet<string>(stringComparer))
.Add(fileName);
foreach (var inc in src.ParsedShader.Includes)
{
if (!resC.TryGetDiskFilePath(inc, out var incFullPath))
{
throw new NotImplementedException();
}
reversePathResolution.GetOrAdd(incFullPath, _ => new HashSet<ResPath>()).Add(path);
var incDir = Path.GetDirectoryName(incFullPath)!;
var incFileName = Path.GetFileName(incFullPath);
dirs.GetOrAdd(incDir, _ => new SortedSet<string>(stringComparer))
.Add(incFileName);
}
++shaderCount;
}
foreach (var (dir, files) in dirs)
{
if (_watchers.TryGetValue(dir, out var watcher))
{
throw new NotImplementedException();
}
watcher = new FileSystemWatcher(dir);
watcher.Changed += (_, ev) =>
{
if (_reloadShadersQueued!.TryAdd(ev.FullPath, true))
{
taskManager.RunOnMainThread(() =>
{
var resPaths = reversePathResolution[ev.FullPath];
foreach (var resPath in resPaths)
{
try
{
_cache.ReloadResource<ShaderSourceResource>(resPath);
shell.WriteLine($"Reloaded shader: {resPath}");
}
catch (Exception)
{
shell.WriteLine($"Failed to reload shader: {resPath}");
}
_reloadShadersQueued.TryRemove(ev.FullPath, out var _);
}
});
}
};
foreach (var file in files)
{
watcher.Filters.Add(file);
}
watcher.EnableRaisingEvents = true;
_watchers.Add(dir, watcher);
++created;
}
shell.WriteLine($"Created {created} shader directory watchers for {shaderCount} shaders.");
return;
}
if (args[0] == "-watch")
{
if (_watchers == null)
{
shell.WriteLine("No shader directory watchers active.");
return;
}
var disposed = 0;
foreach (var (_, watcher) in _watchers)
{
++disposed;
watcher.Dispose();
}
_watchers = null;
shell.WriteLine($"Disposed of {disposed} shader directory watchers.");
return;
}
}
if (args.Length > 1)
{
shell.WriteLine("Not implemented.");
return;
}
shell.WriteLine("Reloading content shader resources...");
foreach (var (path, _) in _cache.GetAllResources<ShaderSourceResource>())
{
try
{
_cache.ReloadResource<ShaderSourceResource>(path);
}
catch (Exception)
{
shell.WriteLine($"Failed to reload shader: {path}");
}
}
shell.WriteLine("Done.");
}
}
internal sealed partial class ClydeDebugLayerCommand : LocalizedCommands
{
[Dependency] private IClydeInternal _clyde = default!;
public override string Command => "cldbglyr";
public override void Execute(IConsoleShell shell, string argStr, string[] args)
{
if (args.Length < 1)
{
_clyde.DebugLayers = ClydeDebugLayers.None;
return;
}
_clyde.DebugLayers = args[0] switch
{
"fov" => ClydeDebugLayers.Fov,
"light" => ClydeDebugLayers.Light,
_ => ClydeDebugLayers.None
};
}
}
internal sealed partial class GetKeyInfoCommand : LocalizedCommands
{
[Dependency] private IClydeInternal _clyde = default!;
public override string Command => "keyinfo";
public override void Execute(IConsoleShell shell, string argStr, string[] args)
{
if (args.Length != 1)
{
shell.WriteLine(Help);
return;
}
if (Enum.TryParse(typeof(Keyboard.Key), args[0], true, out var parsed))
{
var key = (Keyboard.Key)parsed!;
var name = _clyde.GetKeyName(key);
shell.WriteLine($"name: '{name}' ");
}
}
public override CompletionResult GetCompletion(IConsoleShell shell, string[] args)
{
if (args.Length == 1)
{
return CompletionResult.FromOptions(Enum.GetNames<Keyboard.Key>());
}
return CompletionResult.Empty;
}
}
}