-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRenderer.cs
More file actions
986 lines (852 loc) · 41.3 KB
/
Renderer.cs
File metadata and controls
986 lines (852 loc) · 41.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
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Numerics;
using System.Threading.Tasks;
using Silk.NET.Input;
using Silk.NET.OpenGL.Extensions.ImGui;
using ImGuiNET;
using SDL2;
namespace SoftwareRenderer
{
public class Renderer
{
private readonly ConcurrentDictionary<string, Texture> CachedTextures = new();
private readonly Camera Camera = new();
private readonly List<ConnectedPlayer> Players = new();
private readonly List<string> ChatMessages = new();
private MainWindow Window;
private IInputContext InputContext;
private IKeyboard Keyboard;
private IMouse Mouse;
private CharacterController CharacterController;
private Networking NetworkManager;
private Model Dust2Model;
private Model PlayerModel;
private Model GunModel;
private Vector3 SpawnPosition = new Vector3(-16.4f, 1.5f, 6.5f);
private Vector3 SpawnPosition2 = new Vector3(-16.5f, 0.6f, -23);
private Matrix4x4 ModelMatrix = Matrix4x4.CreateScale(0.5f);
private Matrix4x4 GunMatrix = Matrix4x4.CreateScale(0.02f) * Matrix4x4.CreateFromYawPitchRoll(-90 * (MathF.PI / 180), 0, 0);
private Matrix4x4 ProjectionMatrix;
private Vector2 LastMousePosition;
private Quaternion WeaponSway = Quaternion.Identity;
private Quaternion Recoil = Quaternion.Identity;
private float Time;
private float FogStart = 1f;
private float FogEnd = 25f;
private Vector4 FogColor = new Vector4(1f, 0.62f, 0.5f, 1f);
private Vector3 LightEulerDegrees = new(-45, -45, 0);
private Vector3 LightDirection = EulerToDirection(new(-45, -45, 0));
private Vector4 LightColor = Vector4.One;
private Vector3 ClearColor = new Vector3(0.9137f, 0.7098f, 0.6588f);
private float FieldOfView = 90f;
private int RenderedModels;
private bool IsMouseLocked = true;
private bool IsFirstMouse = true;
private bool WasEscapePressed;
private bool WasVPressed;
private bool IsLayoutLoaded;
private bool IsJumpRequested;
private string ChatInput = "";
private bool IsChatWindowOpen = true;
private bool IsChatInputActive;
private bool ScrollToBottom;
private float LastShotTime;
private float ShotCooldown = 0.25f;
private string PlayerName = "Player"; // Default name if file reading fails
private class ConnectedPlayer
{
public int Id { get; set; }
public Vector3 Position { get; set; } = Vector3.Zero;
public Vector3 LocalPosition { get; set; } = Vector3.Zero;
public Quaternion Rotation { get; set; } = Quaternion.Identity;
public float Health { get; set; } = 100f;
public string Name { get; set; } = "Player";
}
public void Main(string[] args)
{
Window = new MainWindow("Software Renderer - Dust2") { RenderScale = 0.25f };
Task.Run(async () =>
{
string ipAddress = args.Length > 0 ? args[0] : "127.0.0.1";
await InitializeNetworkingAsync(ipAddress);
SetupWindowEvents();
LoadPlayerNameFromFile();
NetworkManager.SendRPC("ConnectedPlayer", new[] { NetworkManager.ClientId.ToString(), PlayerName }, BufferRPC: true);
}).Wait();
Window.Run();
}
private void LoadPlayerNameFromFile(string filePath = "./Playername.txt")
{
try
{
if (File.Exists(filePath))
{
PlayerName = File.ReadAllText(filePath).Trim();
if (string.IsNullOrWhiteSpace(PlayerName))
{
PlayerName = $"Player {NetworkManager.ClientId}";
Console.WriteLine($"Warning: {filePath} is empty. Using default name: {PlayerName}");
}
}
else
{
PlayerName = $"Player {NetworkManager.ClientId}";
Console.WriteLine($"Warning: {filePath} not found. Using default name: {PlayerName}");
}
}
catch (Exception ex)
{
PlayerName = $"Player {NetworkManager.ClientId}";
Console.WriteLine($"Error reading {filePath}: {ex.Message}. Using default name: {PlayerName}");
}
}
private async Task InitializeNetworkingAsync(string ipAddress)
{
NetworkManager = new Networking();
if (!await NetworkManager.Connect(ipAddress))
{
Environment.Exit(1);
}
RegisterNetworkCallbacks();
}
private void SetupWindowEvents()
{
Window.StartEvent += InitializeInput;
Window.UpdateEvent += Update;
Window.CloseEvent += Dispose;
}
private void InitializeInput()
{
InputContext = Window.InputContext;
Keyboard = InputContext.Keyboards[0];
Mouse = InputContext.Mice[0];
Mouse.Cursor.CursorMode = CursorMode.Disabled;
Mouse.MouseMove += HandleMouseMovement;
Mouse.MouseDown += HandleMouseClick;
}
private void HandleMouseMovement(IMouse mouse, Vector2 position)
{
if (!IsMouseLocked) return;
if (IsFirstMouse)
{
LastMousePosition = position;
IsFirstMouse = false;
return;
}
var delta = position - LastMousePosition;
LastMousePosition = position;
var euler = Camera.GetEulerAngles();
euler.Y -= delta.X * Camera.Sensitivity;
euler.X = Math.Clamp(euler.X - delta.Y * Camera.Sensitivity, -89f, 89f);
Camera.Rotation = Quaternion.CreateFromYawPitchRoll(
euler.Y * MathF.PI / 180f,
euler.X * MathF.PI / 180f,
euler.Z * MathF.PI / 180f);
}
private void HandleMouseClick(IMouse mouse, MouseButton button)
{
if (button == MouseButton.Left && IsMouseLocked && Time - LastShotTime >= ShotCooldown)
{
Shoot();
LastShotTime = Time;
}
}
private void Shoot()
{
var rayOrigin = Camera.Position;
var rayDirection = Camera.GetFront();
const float maxDistance = 100f;
var closestHit = new { Distance = float.MaxValue, Player = (ConnectedPlayer)null, Point = Vector3.Zero, Normal = Vector3.Zero, IsLevel = false };
Parallel.ForEach(Players, player =>
{
if (player.Id == NetworkManager.ClientId) return;
var playerMatrix = CreatePlayerMatrix(player);
foreach (var mesh in PlayerModel.Meshes)
{
if (Physics.Raycast(rayOrigin, rayDirection, mesh.Vertices.ToArray(), mesh.Indices.ToArray(), playerMatrix,
out float distance, out Vector3 point, out Vector3 normal) && distance < closestHit.Distance)
{
lock (new object())
{
if (distance < closestHit.Distance)
{
closestHit = new { Distance = distance, Player = player, Point = point, Normal = normal, IsLevel = false };
}
}
}
}
});
if (Dust2Model != null)
{
Parallel.ForEach(Dust2Model.Meshes, mesh =>
{
if (Physics.Raycast(rayOrigin, rayDirection, mesh.Vertices.ToArray(), mesh.Indices.ToArray(), ModelMatrix,
out float distance, out Vector3 point, out Vector3 normal) && distance < closestHit.Distance)
{
lock (new object())
{
if (distance < closestHit.Distance)
{
closestHit = new { Distance = distance, Player = (ConnectedPlayer)null, Point = point, Normal = normal, IsLevel = true };
}
}
}
});
}
NetworkManager.SendRPC("Shoot", [Camera.Position.X.ToString(), Camera.Position.Y.ToString(),Camera.Position.Z.ToString()]);
if (closestHit.Distance < maxDistance)
{
if (closestHit.Player != null)
{
const float damage = 10f;
NetworkManager.SendRPC("PlayerHit", new[]
{
closestHit.Player.Id.ToString(),
NetworkManager.ClientId.ToString(),
damage.ToString()
});
}
else if (closestHit.IsLevel)
{
NetworkManager.SendRPC("LevelHit", new[]
{
NetworkManager.ClientId.ToString(),
closestHit.Point.X.ToString(),
closestHit.Point.Y.ToString(),
closestHit.Point.Z.ToString(),
closestHit.Normal.X.ToString(),
closestHit.Normal.Y.ToString(),
closestHit.Normal.Z.ToString()
});
}
ScrollToBottom = true;
}
Recoil *= Quaternion.CreateFromYawPitchRoll(0, 45, 0);
}
private Matrix4x4 CreatePlayerMatrix(ConnectedPlayer player)
{
return Matrix4x4.CreateScale(CharacterController.Height / 2) *
Matrix4x4.CreateFromQuaternion(player.Rotation * Quaternion.CreateFromAxisAngle(Vector3.UnitY, MathF.PI)) *
Matrix4x4.CreateTranslation(player.LocalPosition - Vector3.UnitY * CharacterController.Height / 2);
}
private void Update(double deltaTime)
{
Time += (float)deltaTime;
WeaponSway = Quaternion.Slerp(WeaponSway, Camera.Rotation, 15f * (float)deltaTime);
Recoil = Quaternion.Slerp(Recoil, Quaternion.Identity, 5f * (float)deltaTime);
UpdateNetwork();
UpdateUserInterface((float)deltaTime);
UpdateCharacterController((float)deltaTime);
UpdateInput();
RenderScene((float)deltaTime);
}
private void UpdateNetwork()
{
if (!NetworkManager.IsConnected || CharacterController == null) return;
var eulerDegrees = Camera.GetEulerAngles();
var rotation = Quaternion.CreateFromYawPitchRoll(eulerDegrees.Y * MathF.PI / 180f, 0, 0);
NetworkManager.SendRPC("Update", new[]
{
NetworkManager.ClientId.ToString(),
CharacterController.Position.X.ToString(),
CharacterController.Position.Y.ToString(),
CharacterController.Position.Z.ToString(),
rotation.X.ToString(),
rotation.Y.ToString(),
rotation.Z.ToString(),
rotation.W.ToString()
});
}
private void UpdateUserInterface(float deltaTime)
{
var io = ImGui.GetIO();
io.ConfigFlags |= ImGuiConfigFlags.DockingEnable | ImGuiConfigFlags.ViewportsEnable | ImGuiConfigFlags.DpiEnableScaleViewports;
var viewport = ImGui.GetMainViewport();
ImGui.SetNextWindowPos(viewport.Pos);
ImGui.SetNextWindowSize(viewport.Size);
ImGui.SetNextWindowViewport(viewport.ID);
ImGui.DockSpaceOverViewport(viewport.ID, viewport, ImGuiDockNodeFlags.PassthruCentralNode);
RenderChatWindow();
RenderLocalPlayerHealth();
RenderCrosshair();
if (!IsMouseLocked) RenderDebugUserInterface(deltaTime);
if (!IsLayoutLoaded)
{
ImGui.LoadIniSettingsFromDisk("./Assets/Layouts/DefaultLayout.ini");
IsLayoutLoaded = true;
}
}
private void RenderCrosshair()
{
var viewport = ImGui.GetMainViewport();
var center = new Vector2(viewport.Pos.X + viewport.Size.X / 2, viewport.Pos.Y + viewport.Size.Y / 2);
var drawList = ImGui.GetForegroundDrawList();
float crosshairSize = 10f;
float thickness = 2f;
var color = ImGui.GetColorU32(ImGuiCol.Text);
// Horizontal line
drawList.AddLine(
new Vector2(center.X - crosshairSize, center.Y),
new Vector2(center.X + crosshairSize, center.Y),
color,
thickness
);
// Vertical line
drawList.AddLine(
new Vector2(center.X, center.Y - crosshairSize),
new Vector2(center.X, center.Y + crosshairSize),
color,
thickness
);
}
private void RenderLocalPlayerHealth()
{
var player = Players.Find(p => p.Id == NetworkManager.ClientId);
if (player == null) return;
var viewport = ImGui.GetMainViewport();
var windowSize = new Vector2(200, 50);
var windowPos = new Vector2(
viewport.Pos.X + viewport.Size.X - windowSize.X - 10,
viewport.Pos.Y + viewport.Size.Y - windowSize.Y - 10
);
ImGui.SetNextWindowPos(windowPos, ImGuiCond.Always);
ImGui.SetNextWindowSize(windowSize, ImGuiCond.Always);
if (ImGui.Begin("Player Health", ImGuiWindowFlags.NoResize | ImGuiWindowFlags.NoMove | ImGuiWindowFlags.NoDocking))
{
ImGui.Text($"Health: {player.Health:F0}");
}
ImGui.End();
}
private void UpdateCharacterController(float deltaTime)
{
if (CharacterController == null) return;
var moveInput = Vector3.Zero;
var front = Camera.GetFront();
var right = Vector3.Normalize(Vector3.Cross(front, Vector3.UnitY));
front.Y = 0;
front = Vector3.Normalize(front);
right.Y = 0;
right = Vector3.Normalize(right);
if (!IsChatInputActive)
{
if (Keyboard.IsKeyPressed(Key.W)) moveInput += front;
if (Keyboard.IsKeyPressed(Key.S)) moveInput -= front;
if (Keyboard.IsKeyPressed(Key.A)) moveInput -= right;
if (Keyboard.IsKeyPressed(Key.D)) moveInput += right;
if (Keyboard.IsKeyPressed(Key.Space)) moveInput += Vector3.UnitY;
if (Keyboard.IsKeyPressed(Key.ShiftLeft)) moveInput -= Vector3.UnitY;
IsJumpRequested = Keyboard.IsKeyPressed(Key.Space);
}
CharacterController.Update(deltaTime, moveInput, IsJumpRequested);
Camera.Position = CharacterController.Position + CharacterController.CamOffset;
}
private void UpdateInput()
{
bool isEscapePressed = Keyboard.IsKeyPressed(Key.Escape);
if (isEscapePressed && !WasEscapePressed)
{
IsMouseLocked = !IsMouseLocked;
Mouse.Cursor.CursorMode = IsMouseLocked ? CursorMode.Disabled : CursorMode.Normal;
IsFirstMouse = true;
}
WasEscapePressed = isEscapePressed;
bool isVPressed = Keyboard.IsKeyPressed(Key.V);
if (isVPressed && !WasVPressed && !IsChatInputActive)
{
CharacterController.IsNoClipEnabled = !CharacterController.IsNoClipEnabled;
}
WasVPressed = isVPressed;
}
private void RenderScene(float DeltaTime)
{
ProjectionMatrix = Matrix4x4.CreatePerspectiveFieldOfView(
FieldOfView * MathF.PI / 180,
(float)Window.RenderWidth / Window.RenderHeight,
Rasterizer.NearClip,
Rasterizer.FarClip);
Window.ClearDepthBuffer();
Window.ClearColorBuffer(new Vector4(ClearColor.X, ClearColor.Y, ClearColor.Z, 1f));
RenderDust2();
RenderGun();
RenderConnectedPlayers(DeltaTime);
RenderPlayerNametags();
Window.RenderFrame();
}
private void RenderDust2()
{
if (Dust2Model == null)
{
Dust2Model = new Model().LoadModel("./Assets/dust2/scene.gltf");
Random random = new Random();
double randomValue = random.NextDouble();
bool spawnAtFirst = randomValue > 0.5;
Vector3 spawnPos = spawnAtFirst ? SpawnPosition : SpawnPosition2;
Quaternion cameraRotation = spawnAtFirst ? Quaternion.Identity : Quaternion.CreateFromAxisAngle(Vector3.UnitY, MathF.PI);
Camera.Position = spawnPos;
Camera.Rotation = cameraRotation;
CharacterController = new CharacterController(spawnPos, [Dust2Model.Meshes], [ModelMatrix]);
}
var viewMatrix = Camera.GetViewMatrix();
RenderedModels = 0;
Parallel.ForEach(Dust2Model.Meshes, mesh =>
{
if (!FrustumCuller.IsSphereInFrustum(mesh.SphereBounds, ModelMatrix, viewMatrix, ProjectionMatrix))
return;
var texture = LoadTexture(mesh);
Rasterizer.RenderMesh(
Window,
mesh.Vertices.ToArray(),
mesh.Indices.ToArray(),
ModelMatrix,
viewMatrix,
ProjectionMatrix,
VertexShader,
input => FragmentShader(input, texture),
Rasterizer.CullMode.Back);
lock (new object())
{
RenderedModels++;
}
});
}
private void RenderGun()
{
if (GunModel == null)
{
GunModel = new Model().LoadModel("./Assets/Gun/scene.gltf");
}
var viewMatrix = Camera.GetViewMatrix();
var gunMatrix = GunMatrix * Matrix4x4.CreateFromQuaternion(WeaponSway * Recoil) *
Matrix4x4.CreateTranslation(Camera.Position + Vector3.Transform(new Vector3(0.05f, -0.05f, -0.15f + Math.Abs(Recoil.X / 5)), Camera.Rotation));
Parallel.ForEach(GunModel.Meshes, mesh =>
{
if (!FrustumCuller.IsSphereInFrustum(mesh.SphereBounds, gunMatrix, viewMatrix, ProjectionMatrix))
return;
var texture = LoadTexture(mesh);
Rasterizer.RenderMesh(
Window,
mesh.Vertices.ToArray(),
mesh.Indices.ToArray(),
gunMatrix,
viewMatrix,
ProjectionMatrix,
VertexShader,
input => FragmentShader(input, texture),
Rasterizer.CullMode.Back);
lock (new object())
{
RenderedModels++;
}
});
}
private void RenderConnectedPlayers(float DeltaTime)
{
if (PlayerModel == null)
{
PlayerModel = new Model().LoadModel("./Assets/gordon_freeman/scene.gltf");
}
if (PlayerModel == null || CharacterController == null) return;
var viewMatrix = Camera.GetViewMatrix();
foreach (var player in Players)
{
float InterpolationRate = 12f;
float Factor = 1f - MathF.Exp(-InterpolationRate * DeltaTime);
player.LocalPosition = Vector3.Lerp(player.LocalPosition, player.Position, Factor);
if (player.Id == NetworkManager.ClientId) continue;
var playerMatrix = CreatePlayerMatrix(player);
foreach (var mesh in PlayerModel.Meshes)
{
if (!FrustumCuller.IsSphereInFrustum(mesh.SphereBounds, playerMatrix, viewMatrix, ProjectionMatrix))
continue;
var texture = LoadTexture(mesh);
Rasterizer.RenderMesh(
Window,
mesh.Vertices.ToArray(),
mesh.Indices.ToArray(),
playerMatrix,
viewMatrix,
ProjectionMatrix,
VertexShader,
input => FragmentShader(input, texture),
Rasterizer.CullMode.Back);
}
}
}
private void RenderPlayerNametags()
{
if (Players.Count == 0) return;
var viewMatrix = Camera.GetViewMatrix();
var viewProjection = viewMatrix * ProjectionMatrix;
foreach (var player in Players)
{
if (player.Id == NetworkManager.ClientId) continue;
var headPosition = player.LocalPosition + new Vector3(0, CharacterController.Height / 2f, 0);
var clipPos = Vector4.Transform(new Vector4(headPosition, 1f), viewProjection);
if (clipPos.W <= 0.001f) continue;
var ndc = new Vector3(clipPos.X, clipPos.Y, clipPos.Z) / clipPos.W;
if (ndc.Z < 0 || ndc.Z > 1) continue;
var screenPos = new Vector2(
(ndc.X + 1f) * 0.5f * Window.WindowWidth,
(1f - ndc.Y) * 0.5f * Window.WindowHeight);
if (screenPos.X < 0 || screenPos.X > Window.WindowWidth ||
screenPos.Y < 0 || screenPos.Y > Window.WindowHeight)
continue;
ImGui.SetNextWindowPos(screenPos, ImGuiCond.Always, new Vector2(0.5f, 1f));
ImGui.SetNextWindowBgAlpha(0.35f);
if (ImGui.Begin($"###Nametag_{player.Name}",
ImGuiWindowFlags.NoDecoration |
ImGuiWindowFlags.AlwaysAutoResize |
ImGuiWindowFlags.NoSavedSettings |
ImGuiWindowFlags.NoFocusOnAppearing |
ImGuiWindowFlags.NoNav))
{
ImGui.Text($"{player.Name} - Health: {player.Health:F0}");
ImGui.End();
}
}
}
private void RenderChatWindow()
{
unsafe
{
var viewport = ImGui.GetMainViewport();
var windowSize = new Vector2(400, 300);
var windowPos = new Vector2(viewport.Pos.X + viewport.Size.X - windowSize.X - 10, viewport.Pos.Y + 10);
ImGui.SetNextWindowPos(windowPos, ImGuiCond.Always);
ImGui.SetNextWindowSize(windowSize, ImGuiCond.Always);
if (!ImGui.Begin("Chat", ref IsChatWindowOpen, ImGuiWindowFlags.NoResize | ImGuiWindowFlags.NoMove | ImGuiWindowFlags.NoDocking))
{
ImGui.End();
return;
}
ImGui.BeginChild("ChatContent", new Vector2(0, -ImGui.GetFrameHeightWithSpacing()));
foreach (var message in ChatMessages)
{
if (!string.IsNullOrEmpty(message))
{
ImGui.PushTextWrapPos(0f);
ImGui.TextUnformatted(message);
ImGui.PopTextWrapPos();
}
}
var inputBoxHeight = ImGui.GetFrameHeightWithSpacing();
var scrollMax = ImGui.GetScrollMaxY();
var scrollY = ImGui.GetScrollY();
var lastMessageHeight = ChatMessages.Count > 0 && !string.IsNullOrEmpty(ChatMessages[^1])
? ImGui.CalcTextSize(ChatMessages[^1], false, ImGui.GetContentRegionAvail().X).Y + ImGui.GetStyle().ItemSpacing.Y
: 0f;
if (ScrollToBottom || scrollY >= scrollMax - (lastMessageHeight + inputBoxHeight))
{
ImGui.SetScrollY(scrollMax);
ScrollToBottom = false;
}
ImGui.EndChild();
ImGui.Separator();
var inputTextFlags = ImGuiInputTextFlags.EnterReturnsTrue | ImGuiInputTextFlags.CallbackCompletion | ImGuiInputTextFlags.CallbackHistory;
bool reclaimFocus = false;
if (ImGui.InputText("##ChatInput", ref ChatInput, 256, inputTextFlags, _ => 0))
{
if (!string.IsNullOrWhiteSpace(ChatInput))
{
if (NetworkManager.IsConnected)
{
NetworkManager.SendRPC("ChatMessage", new[] { $"{ Players.Find(p => p.Id == NetworkManager.ClientId)?.Name }", ChatInput });
}
ChatInput = "";
ScrollToBottom = true;
}
reclaimFocus = true;
}
ImGui.SetItemDefaultFocus();
if (reclaimFocus || (IsChatInputActive && !ImGui.IsItemActive()))
{
ImGui.SetKeyboardFocusHere(-1);
}
IsChatInputActive = ImGui.IsItemActive();
ImGui.End();
}
}
private void RenderDebugUserInterface(float deltaTime)
{
ImGui.Begin("Renderer Controls", ImGuiWindowFlags.None);
if (ImGui.CollapsingHeader("Performance", ImGuiTreeNodeFlags.DefaultOpen))
{
ImGui.Text($"FPS: {(int)(1 / deltaTime)}");
ImGui.Text($"Frame Time: {deltaTime * 1000:F2}ms");
ImGui.Text($"Rendered Meshes: {RenderedModels}");
ImGui.Text($"Cached Textures: {CachedTextures.Count}");
}
if (ImGui.CollapsingHeader("Scene Info", ImGuiTreeNodeFlags.DefaultOpen))
{
ImGui.Text($"Loaded Meshes: {Dust2Model.Meshes?.Count ?? 0}");
ImGui.Text($"Runtime: {Time:F2}s");
ImGui.Text($"Window Size: {Window.WindowWidth}x{Window.WindowHeight}");
ImGui.Text($"Render Size: {Window.RenderWidth}x{Window.RenderHeight}");
}
if (ImGui.CollapsingHeader("Multiplayer", ImGuiTreeNodeFlags.DefaultOpen))
{
ImGui.Text("Connected Players:");
foreach (var player in Players)
{
ImGui.Text($"Player ID: {player.Id}");
ImGui.Text($"Player Name: {player.Name}");
ImGui.Text($"Position: {player.Position}");
ImGui.Text($"Rotation: {player.Rotation}");
}
}
if (ImGui.CollapsingHeader("Camera", ImGuiTreeNodeFlags.DefaultOpen))
{
ImGui.Text("Clipping:");
ImGui.DragFloat("Near Clip", ref Rasterizer.NearClip, 0.01f, 0.001f, 1);
Rasterizer.NearClip = Math.Max(Rasterizer.NearClip, 0.001f);
ImGui.DragFloat("Far Clip", ref Rasterizer.FarClip, 0.5f, 0.001f, 1000);
Rasterizer.FarClip = Math.Max(Rasterizer.FarClip, Rasterizer.NearClip + 0.01f);
ImGui.Text("Rotation:");
var eulerDegrees = Camera.GetEulerAngles();
float pitch = eulerDegrees.X;
float yaw = eulerDegrees.Y;
float roll = eulerDegrees.Z;
bool updated = false;
if (ImGui.DragFloat("Pitch (°)", ref pitch, 0.5f))
{
pitch = Math.Clamp(pitch, -89f, 89f);
updated = true;
}
if (ImGui.DragFloat("Yaw (°)", ref yaw, 0.5f)) updated = true;
if (ImGui.DragFloat("Roll (°)", ref roll, 0.5f)) updated = true;
if (updated)
{
Camera.Rotation = Quaternion.CreateFromYawPitchRoll(
yaw * MathF.PI / 180f,
pitch * MathF.PI / 180f,
roll * MathF.PI / 180f);
}
ImGui.SliderFloat("Mouse Sensitivity", ref Camera.Sensitivity, 0.01f, 1f);
ImGui.SliderFloat("FOV", ref FieldOfView, 1f, 179f);
var frontVec = Camera.GetFront();
ImGui.Text($"Front: {frontVec.X:F2}, {frontVec.Y:F2}, {frontVec.Z:F2}");
}
if (CharacterController != null && ImGui.CollapsingHeader("Character Controller", ImGuiTreeNodeFlags.DefaultOpen))
{
var camPos = Camera.Position;
if (ImGui.DragFloat3("Position", ref camPos, 0.1f))
{
Camera.Position = camPos;
CharacterController.Position = camPos;
}
var camOffset = CharacterController.CamOffset;
if (ImGui.DragFloat3("Camera Offset", ref camOffset, 0.1f))
CharacterController.CamOffset = camOffset;
var moveSpeed = CharacterController.MoveSpeed;
if (ImGui.DragFloat("Move Speed", ref moveSpeed, 0.1f, 1f, 20f))
CharacterController.MoveSpeed = moveSpeed;
var maxAirSpeed = CharacterController.MaxAirSpeed;
if (ImGui.DragFloat("Max Air Speed", ref maxAirSpeed, 0.1f, 1f, 20f))
CharacterController.MaxAirSpeed = maxAirSpeed;
var jumpForce = CharacterController.JumpForce;
if (ImGui.DragFloat("Jump Force", ref jumpForce, 0.1f, 1f, 20f))
CharacterController.JumpForce = jumpForce;
var radius = CharacterController.Radius;
if (ImGui.DragFloat("Radius", ref radius, 0.1f, 1f, 20f))
CharacterController.Radius = radius;
var height = CharacterController.Height;
if (ImGui.DragFloat("Height", ref height, 0.1f, 0.5f, 3f))
CharacterController.Height = height;
var groundAccel = CharacterController.GroundAcceleration;
if (ImGui.DragFloat("Ground Acceleration", ref groundAccel, 0.1f, 1f, 20f))
CharacterController.GroundAcceleration = groundAccel;
var airAccel = CharacterController.AirAcceleration;
if (ImGui.DragFloat("Air Acceleration", ref airAccel, 0.1f, 1f, 20f))
CharacterController.AirAcceleration = airAccel;
var groundFriction = CharacterController.GroundFriction;
if (ImGui.DragFloat("Ground Friction", ref groundFriction, 0.1f, 1f, 20f))
CharacterController.GroundFriction = groundFriction;
var airControl = CharacterController.AirControl;
if (ImGui.DragFloat("Air Control", ref airControl, 0.01f, 0f, 1f))
CharacterController.AirControl = airControl;
var stepSize = CharacterController.StepSize;
if (ImGui.DragFloat("Step Size", ref stepSize, 0.1f, 0.5f, 3f))
CharacterController.StepSize = stepSize;
var gravity = CharacterController.Gravity;
if (ImGui.DragFloat3("Gravity", ref gravity, 0.1f, -20f, 20f))
CharacterController.Gravity = gravity;
ImGui.Text($"Velocity: {CharacterController.Velocity.X:F2}, {CharacterController.Velocity.Y:F2}, {CharacterController.Velocity.Z:F2}");
ImGui.Text($"Is Grounded: {CharacterController.IsGrounded}");
}
if (ImGui.CollapsingHeader("Rendering", ImGuiTreeNodeFlags.DefaultOpen))
{
ImGui.Text($"Render Scale: {(int)(Window.RenderScale * 100)}%%");
if (ImGui.SliderFloat("##RenderScale", ref Window.RenderScale, 0.1f, 1f))
{
Window.UpdateRenderScale(Window.RenderScale);
}
ImGui.Text("Clear Color:");
ImGui.ColorEdit3("Clear Color", ref ClearColor);
ImGui.Text("Debug Modes:");
int debugMode = (int)Rasterizer.RenderDebugMode;
ImGui.RadioButton("Normal", ref debugMode, (int)Rasterizer.DebugMode.None);
ImGui.SameLine();
ImGui.RadioButton("Wireframe", ref debugMode, (int)Rasterizer.DebugMode.Wireframe);
Rasterizer.RenderDebugMode = (Rasterizer.DebugMode)debugMode;
ImGui.Text("Fog Settings:");
ImGui.SliderFloat("Fog Start", ref FogStart, 1f, 100f);
ImGui.SliderFloat("Fog End", ref FogEnd, 10f, 500f);
ImGui.ColorEdit4("Fog Color", ref FogColor);
ImGui.Text("Light Settings:");
if (ImGui.DragFloat3("Light Rotation", ref LightEulerDegrees, 0.5f))
{
LightDirection = EulerToDirection(LightEulerDegrees);
}
ImGui.ColorEdit4("Light Color", ref LightColor);
}
ImGui.End();
}
private Texture LoadTexture(Mesh mesh)
{
if (mesh?.Material?.TexturePaths?.TryGetValue(TextureSlot.Diffuse, out var texturePath) == true)
{
return CachedTextures.GetOrAdd(texturePath, path => Texture.LoadTexture(path));
}
return null;
}
private Shaders.VertexOutput VertexShader(Shaders.VertexInput vertex, Matrix4x4 modelMatrix, Matrix4x4 viewMatrix, Matrix4x4 projectionMatrix)
{
var worldPos = Vector4.Transform(new Vector4(vertex.Position, 1), modelMatrix);
var viewPos = Vector4.Transform(worldPos, viewMatrix);
var clipPos = Vector4.Transform(viewPos, projectionMatrix);
var worldNormal = Vector3.Normalize(Vector3.TransformNormal(vertex.Normal, modelMatrix));
return new Shaders.VertexOutput
{
ClipPosition = clipPos,
Data = { ["WorldNormal"] = worldNormal },
TexCoord = vertex.UV,
Color = vertex.Color,
Normal = vertex.Normal,
Interpolate = true
};
}
private Vector4 FragmentShader(Shaders.VertexOutput input, Texture texture = null)
{
var worldNormal = (Vector3)input.Data["WorldNormal"];
var diffuse = MathF.Max(0.25f, Vector3.Dot(worldNormal, -LightDirection));
var textureColor = texture?.Sample(input.TexCoord) ?? Vector4.One;
var baseColor = input.Color * textureColor;
var depth = input.ClipPosition.Z;
var fogFactor = Math.Clamp((FogEnd - depth) / (FogEnd - FogStart), 0f, 1f);
fogFactor = fogFactor * fogFactor * (3f - 2f * fogFactor);
var finalColor = Vector4.Lerp(FogColor, baseColor * (0.1f + 0.9f * diffuse) * LightColor, fogFactor);
return new Vector4(finalColor.X, finalColor.Y, finalColor.Z, baseColor.W);
}
private void RegisterNetworkCallbacks()
{
if (!NetworkManager.IsConnected) return;
NetworkManager.OnReceiveRPC += async (method, parameters) =>
{
switch (method)
{
case "ConnectedPlayer"
when parameters.Length >= 2 && int.TryParse(parameters[0], out int newPlayerId):
Players.Add(new ConnectedPlayer { Id = newPlayerId, Name = parameters[1], Health = 100f });
ChatMessages.Add($"{parameters[1]} has joined the game!");
ScrollToBottom = true;
break;
case "Update" when parameters.Length >= 8 && int.TryParse(parameters[0], out int playerId):
var player = Players.Find(p => p.Id == playerId);
if (player != null)
{
player.Position = new Vector3(
float.Parse(parameters[1]),
float.Parse(parameters[2]),
float.Parse(parameters[3]));
player.Rotation = new Quaternion(
float.Parse(parameters[4]),
float.Parse(parameters[5]),
float.Parse(parameters[6]),
float.Parse(parameters[7]));
}
break;
case "DisconnectedPlayer"
when parameters.Length >= 1 && int.TryParse(parameters[0], out int disconnectedId):
var disconnectedPlayer = Players.Find(p => p.Id == disconnectedId);
if (disconnectedPlayer != null)
{
Players.Remove(disconnectedPlayer);
Console.WriteLine($"Player disconnected: {disconnectedPlayer.Name}");
}
break;
case "ChatMessage" when parameters.Length >= 2:
ChatMessages.Add($"{parameters[0]}: {parameters[1]}");
ScrollToBottom = true;
break;
case "PlayerHit" when parameters.Length >= 3 && int.TryParse(parameters[0], out int hitPlayerId) &&
float.TryParse(parameters[2], out float damage):
var hitPlayer = Players.Find(p => p.Id == hitPlayerId);
if (hitPlayer != null)
{
hitPlayer.Health = Math.Max(0f, hitPlayer.Health - damage);
if (hitPlayer.Health <= 0f)
{
ChatMessages.Add($"{hitPlayer.Name} was killed!");
if (NetworkManager.ClientId == hitPlayerId && CharacterController != null)
{
Random random = new Random();
double randomValue = random.NextDouble();
bool spawnAtFirst = randomValue > 0.5;
Vector3 spawnPos = spawnAtFirst ? SpawnPosition : SpawnPosition2;
Quaternion cameraRotation = spawnAtFirst
? Quaternion.Identity
: Quaternion.CreateFromAxisAngle(Vector3.UnitY, MathF.PI);
CharacterController.Position = spawnPos;
Camera.Rotation = cameraRotation;
}
hitPlayer.Health = 100f;
NetworkManager.SendRPC("Update", new[]
{
hitPlayer.Id.ToString(),
hitPlayer.Position.X.ToString(),
hitPlayer.Position.Y.ToString(),
hitPlayer.Position.Z.ToString(),
hitPlayer.Rotation.X.ToString(),
hitPlayer.Rotation.Y.ToString(),
hitPlayer.Rotation.Z.ToString(),
hitPlayer.Rotation.W.ToString()
});
}
ScrollToBottom = true;
}
break;
case "Shoot":
Console.WriteLine("Shot sound");
Vector3 Position = new Vector3(
float.Parse(parameters[0]),
float.Parse(parameters[1]),
float.Parse(parameters[2]));
float Distance = Vector3.Distance(Camera.Position, Position);
float Volume = Math.Clamp(25f / (0.25f * Distance), 0f, 25f); // SFML style volume 0-100
string FilePath = Path.Combine(AppContext.BaseDirectory, "Assets/pistol.wav");
Sounds.PlaySound(FilePath, Volume / 100);
break;
}
};
}
private static Vector3 EulerToDirection(Vector3 eulerDegrees)
{
var radians = eulerDegrees * MathF.PI / 180f;
var rotation = Matrix4x4.CreateFromYawPitchRoll(radians.Y, radians.X, radians.Z);
return Vector3.Normalize(Vector3.Transform(-Vector3.UnitZ, rotation));
}
public void Dispose()
{
if (NetworkManager?.IsConnected == true)
{
NetworkManager.SendRPC("DisconnectedPlayer", new[] { NetworkManager.ClientId.ToString() });
NetworkManager.Close();
}
CachedTextures.Clear();
InputContext?.Dispose();
GC.SuppressFinalize(this);
}
}
}