-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGraphics.cs
More file actions
1368 lines (1250 loc) · 56.3 KB
/
Graphics.cs
File metadata and controls
1368 lines (1250 loc) · 56.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
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using JLGraphics.Input;
using JLGraphics.Rendering;
using JLGraphics.RenderPasses;
using JLUtility;
using OpenTK.Graphics.OpenGL4;
using OpenTK.Mathematics;
using OpenTK.Windowing.Common;
using OpenTK.Windowing.Desktop;
using StbImageSharp;
using StbiSharp;
using Debug = JLUtility.Debug;
namespace JLGraphics
{
public static class GlobalUniformNames
{
readonly static public string SkyBox = "SkyBox";
readonly static public string ViewProjectionMatrix = "ProjectionViewMatrix";
readonly static public string SkyBoxIntensity = "skyBoxIntensity";
readonly static public string AmbientSkyColor = "SkyColor";
readonly static public string AmbientHorizonColor = "HorizonColor";
readonly static public string AmbientGroundColor = "GroundColor";
readonly static public string DepthTexture = "_CameraDepthTexture";
readonly static public string CameraNormalTexture = "_CameraNormalTexture";
readonly static public string SSAOTexture = "AOTex";
readonly static public string SSRTexture = "_SSRColor";
readonly static public string SSGITexture = "_SSGIColor";
}
public struct Time
{
public static float FixedDeltaTime { get => Graphics.Instance.FixedDeltaTime; set => Graphics.Instance.FixedDeltaTime = Math.Clamp(value, float.Epsilon, 1.0f); }
public static float UnscaledDeltaTime => Graphics.Instance.DeltaTime;
public static float UnscaledSmoothDeltaTime => Graphics.Instance.SmoothDeltaTime;
public static float DeltaTime => Graphics.Instance.DeltaTime * TimeScale;
public static float SmoothDeltaTime => Graphics.Instance.SmoothDeltaTime * TimeScale;
public static float ElapsedTime => Graphics.Instance.ElapsedTime * TimeScale;
private static float m_timeScale = 1.0f;
public static float TimeScale { get => m_timeScale; set => m_timeScale = Math.Clamp(value, 0, float.MaxValue); }
}
public struct GraphicsDebug
{
public int MaterialUpdateCount;
public int TotalWorldEntities;
public int MeshBindCount;
public int UseProgramCount;
public int TotalVertices;
public int DrawCount;
public int FrustumCulledEntitiesCount;
public bool DrawAABB;
public bool PauseFrustumCulling;
}
public enum DepthPrePassMode
{
None = 0,
DepthOnly = 1,
MotionVectors = 2
}
public sealed class Graphics : IDisposable
{
static Lazy<Graphics> m_lazyGraphics = new Lazy<Graphics>(() => new Graphics());
public static Graphics Instance { get { return m_lazyGraphics.Value; } }
private Graphics()
{
}
public bool BlitFinalResultsToScreen { get; set; } = true;
public const int MAXPOINTLIGHTS = 128;
public GameWindow Window { get; private set; } = null;
private Vector2i RenderBufferSize { get; set; }
public Vector2i GetRenderSize()
{
return RenderBufferSize;
}
public bool RenderGUI { get; private set; } = false;
public Shader DefaultMaterial { get; private set; } = null;
internal float FixedDeltaTime { get; set; } = 0;
internal float DeltaTime { get; private set; } = 0;
internal float SmoothDeltaTime { get; private set; } = 0;
internal float ElapsedTime { get; private set; } = 0;
private bool m_isInit = false;
private List<Entity> AllInstancedObjects => InternalGlobalScope<Entity>.Values;
private List<Camera> AllCameras => InternalGlobalScope<Camera>.Values;
public Vector2i OutputResolution => new Vector2i((int)(GetRenderSize().X * RenderScale), (int)(GetRenderSize().Y * RenderScale));
FileTracker fileTracker;
public bool GetFileTracker(out FileTracker fileTracker)
{
fileTracker = this.fileTracker;
if(fileTracker == null)
{
return false;
}
return true;
}
private void InitWindow(int msaaSamples, GameWindowSettings m_gameWindowSettings, NativeWindowSettings m_nativeWindowSettings)
{
m_nativeWindowSettings.NumberOfSamples = msaaSamples;
if (Window != null)
{
m_nativeWindowSettings.SharedContext = Window.Context;
Window.Dispose();
}
Window = new GameWindow(m_gameWindowSettings, m_nativeWindowSettings);
RenderBufferSize = Window.Size;
Window.VSync = 0;
Window.Resize += (e) => {
Resize(e);
Window.Size = new Vector2i(WindowResizeResults.X, WindowResizeResults.Y);
};
GL.Enable(EnableCap.DepthTest);
GL.Enable(EnableCap.CullFace);
GL.Enable(EnableCap.Dither);
GL.Enable(EnableCap.Blend);
GL.ClipControl(ClipOrigin.LowerLeft, ClipDepthMode.ZeroToOne);
if (msaaSamples != 0)
{
GL.Enable(EnableCap.Multisample);
}
MouseInput.UpdateMousePosition(Window.MouseState.Position);
MouseInput.UpdateMousePosition(Window.MouseState.Position);
Window.UpdateFrame += UpdateFrame;
}
ShaderProgram DefaultShaderProgram;
ShaderProgram PassthroughShaderProgram;
ShaderProgram DepthPrepassShaderProgram;
float previousRenderScale = 1.0f;
public GraphicsDebug GraphicsDebug;
public bool ReverseDepth { get; set; } = false;
private DepthPrePassMode depthPrePassMode = DepthPrePassMode.None;
public DepthPrePassMode DepthPrepass {
get
{
return depthPrePassMode;
}
set
{
depthPrePassMode = value;
if (value == DepthPrePassMode.None)
{
DefaultMaterial.DepthMask = true;
DefaultMaterial.DepthTestFunction = DepthFunction.Lequal;
SkyboxShader.DepthMask = true;
SkyboxShader.DepthTestFunction = DepthFunction.Lequal;
}
else
{
DefaultMaterial.DepthMask = false;
DefaultMaterial.DepthTestFunction = DepthFunction.Equal;
SkyboxShader.DepthMask = false;
SkyboxShader.DepthTestFunction = DepthFunction.Lequal;
}
}
}
public float RenderScale { get; set; } = 1.0f;
void InitFramebuffers() {
if (MainFrameBuffer != null)
{
MainFrameBuffer.Dispose();
DepthTextureBuffer.Dispose();
}
float scale = RenderScale;// MathF.Sqrt(RenderScale);
var colorSettings = new TFP()
{
wrapMode = TextureWrapMode.MirroredRepeat,
maxMipmap = 11,
minFilter = TextureMinFilter.LinearMipmapNearest,
magFilter = TextureMagFilter.Linear,
internalFormat = PixelInternalFormat.Rgb32f,
};
var normalBufferSettings = new TFP()
{
wrapMode = TextureWrapMode.MirroredRepeat,
maxMipmap = 0,
minFilter = TextureMinFilter.Linear,
magFilter = TextureMagFilter.Linear,
internalFormat = PixelInternalFormat.Rgb16f,
};
var specularMetal = new TFP()
{
wrapMode = TextureWrapMode.MirroredRepeat,
maxMipmap = 11,
minFilter = TextureMinFilter.LinearMipmapNearest,
magFilter = TextureMagFilter.Linear,
internalFormat = PixelInternalFormat.Rgba8,
};
var depthSettings = new TFP() {
wrapMode = TextureWrapMode.ClampToEdge,
maxMipmap = 0,
minFilter = TextureMinFilter.Linear,
magFilter = TextureMagFilter.Linear,
internalFormat = PixelInternalFormat.DepthComponent32f,
};
var depthSettingsColor = new TFP()
{
wrapMode = TextureWrapMode.ClampToEdge,
maxMipmap = 0,
minFilter = TextureMinFilter.Linear,
magFilter = TextureMagFilter.Linear,
internalFormat = PixelInternalFormat.R32f,
};
var windowSize = GetRenderSize();
MainFrameBuffer = new FrameBuffer((int)MathF.Ceiling(windowSize.X * scale), (int)MathF.Ceiling(windowSize.Y * scale), false, colorSettings, normalBufferSettings, specularMetal, depthSettings);
MainFrameBuffer.SetName("Main frame buffer");
DepthTextureBuffer = new FrameBuffer((int)MathF.Ceiling(windowSize.X * scale), (int)MathF.Ceiling(windowSize.Y * scale), false, depthSettingsColor);
DepthTextureBuffer.SetName("Depth texture buffer");
Shader.SetGlobalTexture(Shader.GetShaderPropertyId("_CameraDepthTexture"), DepthTextureBuffer.TextureAttachments[0]);
Shader.SetGlobalTexture(Shader.GetShaderPropertyId("_CameraNormalTexture"), MainFrameBuffer.TextureAttachments[1]);
Shader.SetGlobalTexture(Shader.GetShaderPropertyId("_CameraSpecularTexture"), MainFrameBuffer.TextureAttachments[2]);
Shader.TextureNullIsWhiteOrBlack = false;
Shader.SetGlobalTexture(Shader.GetShaderPropertyId(GlobalUniformNames.SSRTexture), Shader.BlackDefaultTexture);
Shader.SetGlobalTexture(Shader.GetShaderPropertyId(GlobalUniformNames.SSGITexture), Shader.BlackDefaultTexture);
Shader.SetGlobalTexture(Shader.GetShaderPropertyId(GlobalUniformNames.SSAOTexture), Shader.BlackDefaultTexture);
Shader.TextureNullIsWhiteOrBlack = true;
}
public void Init(string windowName, Vector2i windowResolution, float renderFrequency, float fixedUpdateFrequency)
{
m_isInit = true;
previousRenderScale = RenderScale;
StbImage.stbi_set_flip_vertically_on_load(1);
Stbi.SetFlipVerticallyOnLoad(true);
FixedDeltaTime = 1.0f / fixedUpdateFrequency;
var m_gameWindowSettings = GameWindowSettings.Default;
var m_nativeWindowSettings = NativeWindowSettings.Default;
//m_gameWindowSettings.UpdateFrequency = renderFrequency;
m_gameWindowSettings.UpdateFrequency = renderFrequency;
m_nativeWindowSettings.Size = windowResolution;
m_nativeWindowSettings.Title = windowName;
m_nativeWindowSettings.IsEventDriven = false;
m_nativeWindowSettings.API = ContextAPI.OpenGL;
m_nativeWindowSettings.APIVersion = Version.Parse("4.1");
InitWindow(0, m_gameWindowSettings, m_nativeWindowSettings);
var defaultShader = new ShaderProgram("DefaultShader",
AssetLoader.GetPathToAsset("./Shaders/fragment.glsl"),
AssetLoader.GetPathToAsset("./Shaders/vertex.glsl"));
var passThroughShader = new ShaderProgram("PassThroughShader",
AssetLoader.GetPathToAsset("./Shaders/CopyToScreen.frag"),
AssetLoader.GetPathToAsset("./Shaders/Passthrough.vert"));
var depthOnlyShader = new ShaderProgram("DepthOnlyShader",
AssetLoader.GetPathToAsset("./Shaders/DepthOnly.frag"),
AssetLoader.GetPathToAsset("./Shaders/vertexSimple.glsl"));
var skyBoxShaderProrgam = new ShaderProgram("Skybox Shader",
AssetLoader.GetPathToAsset("./Shaders/SkyBoxFrag.glsl"),
AssetLoader.GetPathToAsset("./Shaders/skyboxVert.glsl"));
var skyboxDepthPrepassProgram = new ShaderProgram("Skybox Shader",
AssetLoader.GetPathToAsset("./Shaders/fragmentEmpty.glsl"),
AssetLoader.GetPathToAsset("./Shaders/skyboxVert.glsl"));
#if DEBUG
fileTracker = new FileTracker();
fileTracker.AddFileObject(defaultShader.FragFile);
fileTracker.AddFileObject(defaultShader.VertFile);
fileTracker.AddFileObject(passThroughShader.FragFile);
fileTracker.AddFileObject(passThroughShader.VertFile);
#endif
skyBoxShaderProrgam.CompileProgram();
defaultShader.CompileProgram();
passThroughShader.CompileProgram();
depthOnlyShader.CompileProgram();
skyboxDepthPrepassProgram.CompileProgram();
if (ReverseDepth)
{
Extensions.ReverseDepthBuffer = true;
}
DefaultShaderProgram = defaultShader;
PassthroughShaderProgram = passThroughShader;
DepthPrepassShaderProgram = depthOnlyShader;
SkyboxShader = new Shader("Skybox material", skyBoxShaderProrgam);
SkyboxDepthPrepassShader = new Shader("Skybox depth prepass material", skyboxDepthPrepassProgram);
SkyboxDepthPrepassShader.DepthTestFunction = ReverseDepth ? DepthFunction.Greater : DepthFunction.Less;
SkyboxDepthPrepassShader.DepthMask = true;
SkyboxDepthPrepassShader.DepthTest = true;
SkyboxDepthPrepassShader.ColorMask[1] = true;
SkyboxDepthPrepassShader.ColorMask[2] = false;
SkyboxDepthPrepassShader.ColorMask[2] = false;
SkyboxDepthPrepassShader.ColorMask[3] = false;
DefaultMaterial = new Shader("Default Material", DefaultShaderProgram);
DefaultMaterial.DepthMask = false;
DefaultMaterial.DepthTest = true;
DefaultMaterial.DepthTestFunction = DepthFunction.Equal;
DepthPrepassShader = new Shader("Default depth only", DepthPrepassShaderProgram);
DepthPrepassShader.DepthTestFunction = ReverseDepth ? DepthFunction.Greater : DepthFunction.Less;
DepthPrepassShader.DepthMask = true;
DepthPrepassShader.DepthTest = true;
DepthPrepassShader.ColorMask[0] = true;
DepthPrepassShader.ColorMask[1] = false;
DepthPrepassShader.ColorMask[2] = false;
DepthPrepassShader.ColorMask[3] = false;
DefaultMaterial.SetVector3(Shader.GetShaderPropertyId(DefaultMaterialUniforms.AlbedoColor), new Vector3(1, 1, 1));
DefaultMaterial.SetFloat(Shader.GetShaderPropertyId(DefaultMaterialUniforms.Smoothness), 0.5f);
DefaultMaterial.SetFloat(Shader.GetShaderPropertyId(DefaultMaterialUniforms.Metalness), 0.0f);
DefaultMaterial.SetFloat(Shader.GetShaderPropertyId(DefaultMaterialUniforms.NormalsStrength), 1.0f);
DefaultMaterial.SetVector2(Shader.GetShaderPropertyId(DefaultMaterialUniforms.UvScale), Vector2.One);
FullScreenQuad = Mesh.CreateQuadMesh();
BasicCube = Mesh.CreateCubeMesh();
PassthroughShader = new Shader("Default Passthrough", PassthroughShaderProgram);
InitFramebuffers();
DepthPrepass = DepthPrePassMode.None;
SkyboxController.Init(SkyboxShader);
Batching.Init();
}
public void Dispose()
{
if (m_isInit)
{
Debug.Log("Graphics is not initialized!", Debug.Flag.Error);
}
temporaryUpdateFrameCommands.Clear();
SkyboxDepthPrepassShader.Program.Dispose();
SkyboxShader.Program.Dispose();
AABBDebugShader?.Program.Dispose();
Window.Close();
Window.Dispose();
MainFrameBuffer = null;
DepthTextureBuffer = null;
PassthroughShader = null;
MainFrameBuffer = null;
DefaultMaterial = null;
Window = null;
fileTracker = null;
for (int i = 0; i < renderPasses.Count; i++)
{
renderPasses[i].Dispose();
}
renderPasses = null;
DefaultShaderProgram.Dispose();
PassthroughShaderProgram.Dispose();
DepthPrepassShaderProgram.Dispose();
Mesh.FreeMeshObject(FullScreenQuad);
m_isInit = false;
m_lazyGraphics = new Lazy<Graphics>(() => new Graphics());
DestructorCommands.Instance.ExecuteCommands();
Batching.Free();
}
public void Run()
{
if (!m_isInit)
{
Debug.Log("Graphics not initialized!", Debug.Flag.Error);
throw new Exception("Graphics not initialized!");
}
Window.Run();
}
float fixedTimer = 0;
int frameIncrement = 0;
List<Action> temporaryUpdateFrameCommands = new List<Action>();
float smoothDeltaCount = 0;
private void UpdateFrame(FrameEventArgs eventArgs)
{
MouseInput.UpdateMousePosition(Window.MouseState.Position);
PerfTimer.Start("UpdateFrame");
DeltaTime = (float)Window.UpdateTime;
smoothDeltaCount = MathF.Min(++smoothDeltaCount, 60);
SmoothDeltaTime = SmoothDeltaTime * (1.0f - 1.0f / smoothDeltaCount) + DeltaTime * (1.0f / smoothDeltaCount);
ElapsedTime += DeltaTime;
//do any one time update frame actions
if (temporaryUpdateFrameCommands.Count > 0)
{
for (int i = 0; i < temporaryUpdateFrameCommands.Count; i++)
{
temporaryUpdateFrameCommands[i].Invoke();
}
temporaryUpdateFrameCommands.Clear();
}
InvokeNewStarts();
PerfTimer.Start("UpdateFrame::FixedUpdate");
fixedTimer += Time.DeltaTime;
if (fixedTimer >= Time.FixedDeltaTime)
{
float t = fixedTimer / Time.FixedDeltaTime;
int howMany = (int)MathF.Floor(t);
for (int i = 0; i < howMany; i++)
{
FixedUpdate();
}
fixedTimer = 0;
}
PerfTimer.Stop();
PerfTimer.Start("UpdateFrame::Update");
InvokeUpdates();
PerfTimer.Stop();
float updateFreq = 1.0f / FixedDeltaTime;
#if DEBUG
fileTracker.ResolveFileTrackQueue();
#endif
PerfTimer.Start("UpdateFrame::Stat display");
string stats = "";
stats += " | fixed delta time: " + FixedDeltaTime;
stats += " | draw count: " + GraphicsDebug.DrawCount;
stats += " | cull count: " + GraphicsDebug.FrustumCulledEntitiesCount;
stats += " | shader mesh bind count: " + GraphicsDebug.UseProgramCount + ", " + GraphicsDebug.MeshBindCount;
stats += " | material update count: " + GraphicsDebug.MaterialUpdateCount;
stats += " | vertices: " + GraphicsDebug.TotalVertices;
stats += " | total world objects: " + AllInstancedObjects.Count;
stats += " | fps: " + 1.0f / SmoothDeltaTime;
stats += " | delta time: " + SmoothDeltaTime;
Window.Title = stats;
GraphicsDebug.DrawCount = 0;
GraphicsDebug.UseProgramCount = 0;
GraphicsDebug.MaterialUpdateCount = 0;
GraphicsDebug.MeshBindCount = 0;
GraphicsDebug.TotalVertices = 0;
GraphicsDebug.FrustumCulledEntitiesCount = 0;
PerfTimer.Stop();
PerfTimer.Start("UpdateFrame::RenderScaleChange");
RenderScaleChange(RenderScale);
PerfTimer.Stop();
frameIncrement++;
Shader.SetGlobalInt(Shader.GetShaderPropertyId("_Frame"), frameIncrement);
PerfTimer.Start("UpdateFrame::DoRenderUpdate");
DoRenderUpdate();
PerfTimer.Stop();
Renderer.RendererAddedOrDestroyed = false;
PerfTimer.Start("UpdateFrame::SwapBuffers");
if(BlitFinalResultsToScreen)
Window.SwapBuffers();
PerfTimer.Stop();
DestructorCommands.Instance.ExecuteCommands();
PerfTimer.Stop();
PerfTimer.ResetTimers(true);
}
private bool WindowResized = false;
private Vector2i WindowResizeResults;
private void Resize(ResizeEventArgs args)
{
if (args.Width == WindowResizeResults.X && args.Height == WindowResizeResults.X)
{
return;
}
WindowResizeResults = new Vector2i(args.Width, args.Height);
if (!WindowResized)
{
temporaryUpdateFrameCommands.Add(DoResize);
WindowResized = true;
}
void DoResize()
{
WindowResizeResults.X = (int)MathF.Max(16, WindowResizeResults.X);
WindowResizeResults.Y = (int)MathF.Max(16, WindowResizeResults.Y);
Debug.Log("Window resized: " + WindowResizeResults);
RenderBufferSize = new Vector2i(WindowResizeResults.X, WindowResizeResults.Y);
WindowResized = false;
InitFramebuffers();
GL.Viewport(0, 0, WindowResizeResults.X, WindowResizeResults.Y);
}
}
public void ResizeRenderSize(int width, int height)
{
Resize(new ResizeEventArgs(width, height));
}
private bool RenderScaleChanged = false;
private void RenderScaleChange(float newScale)
{
RenderScale = MathHelper.Clamp(newScale, 0.1f, 2.0f);
if(previousRenderScale == RenderScale)
{
return;
}
previousRenderScale = RenderScale;
void DoRenderScaleChange()
{
Debug.Log("Render Scale Update: " + RenderScale);
InitFramebuffers();
RenderScaleChanged = false;
}
if (!RenderScaleChanged)
{
temporaryUpdateFrameCommands.Add(DoRenderScaleChange);
RenderScaleChanged = true;
}
}
private void InvokeNewStarts()
{
for (int i = 0; i < InternalGlobalScope<IStart>.Count; i++)
{
var current = InternalGlobalScope<IStart>.Values[i];
if (!current.IsActiveAndEnabled())
{
continue;
}
current.Start();
}
InternalGlobalScope<IStart>.Clear();
}
private void FixedUpdate()
{
for (int i = 0; i < InternalGlobalScope<IFixedUpdate>.Count; i++)
{
var current = InternalGlobalScope<IFixedUpdate>.Values[i];
if (current.IsActiveAndEnabled())
{
current.FixedUpdate();
}
}
}
void InvokeUpdates()
{
for (int i = 0; i < InternalGlobalScope<IUpdate>.Count; i++)
{
var current = InternalGlobalScope<IUpdate>.Values[i];
if (!current.IsActiveAndEnabled())
{
continue;
}
current.Update();
}
}
void InvokeOnRenders(Camera camera)
{
//invoke render event
for (int i = 0; i < InternalGlobalScope<IOnRender>.Count; i++)
{
var current = InternalGlobalScope<IOnRender>.Values[i];
if (!current.IsActiveAndEnabled())
{
continue;
}
current.OnRender(camera);
}
}
void SetShaderCameraData(Camera camera)
{
Shader.SetGlobalMat4(Shader.GetShaderPropertyId("ProjectionMatrix"), camera.ProjectionMatrix);
Shader.SetGlobalMat4(Shader.GetShaderPropertyId("InvProjectionMatrix"), camera.ProjectionMatrix.Inverted());
Shader.SetGlobalMat4(Shader.GetShaderPropertyId("ViewMatrix"), camera.ViewMatrix);
Shader.SetGlobalMat4(Shader.GetShaderPropertyId("InvViewMatrix"), camera.ViewMatrix.Inverted());
var vp = camera.ViewMatrix * camera.ProjectionMatrix;
Shader.SetGlobalMat4(Shader.GetShaderPropertyId("InvProjectionViewMatrix"), vp.Inverted());
Shader.SetGlobalMat4(Shader.GetShaderPropertyId("ProjectionViewMatrix"), vp);
Shader.SetGlobalVector3(Shader.GetShaderPropertyId("CameraWorldSpacePos"), camera.Transform.LocalPosition);
Shader.SetGlobalVector3(Shader.GetShaderPropertyId("CameraDirection"), camera.Transform.Forward);
Shader.SetGlobalVector4(Shader.GetShaderPropertyId("CameraParams"), new Vector4(camera.Fov, camera.Width / camera.Height, camera.Near, camera.Far));
Shader.SetGlobalVector2(Shader.GetShaderPropertyId("RenderSize"), new Vector2(camera.Width * RenderScale, camera.Height * RenderScale));
Shader.SetGlobalFloat(Shader.GetShaderPropertyId("RenderScale"), RenderScale);
}
GlMeshObject FullScreenQuad;
GlMeshObject BasicCube;
public Shader PassthroughShader { get; private set; } = null;
public Shader DepthPrepassShader { get; private set; } = null;
public Shader SkyboxShader { get; private set; } = null;
Shader SkyboxDepthPrepassShader;
FrameBuffer MainFrameBuffer = null;
FrameBuffer DepthTextureBuffer = null;
public FrameBuffer FinalRenderTarget => MainFrameBuffer;
internal void Blit(FrameBuffer src, FrameBuffer dst, bool restoreSrc, Shader shader = null, int srcTextureIndex = 0, int dstTextureIndex = 0)
{
StartBlitUnsafe(shader);
BlitUnsafe(src, dst, srcTextureIndex, dstTextureIndex);
EndBlitUnsafe(shader);
if (dst != null)
{
for (int i = 0; i < dst.TextureAttachments.Length; i++)
{
if (dst.TextureAttachments[i].generateMipMaps)
{
GL.GenerateTextureMipmap(dst.TextureAttachments[i].GlTextureID);
}
}
}
if (restoreSrc)
{
FrameBuffer.BindFramebuffer(src);
}
}
bool blitUnsafeFlag = false;
Shader unsafeBlitShader = null;
internal void StartBlitUnsafe(Shader shader)
{
if (blitUnsafeFlag)
{
Debug.Log("StartBlitUnsafe already started!", Debug.Flag.Error);
}
blitUnsafeFlag = true;
Shader blitShader = shader ?? PassthroughShader;
blitShader.DepthTest = false;
this.unsafeBlitShader = blitShader;
}
internal void BlitUnsafe(FrameBuffer src, FrameBuffer dst, int srcTextureIndex, int dstColorAttachIndex)
{
if (!blitUnsafeFlag)
{
Debug.Log("BlitUnsafe out of range!", Debug.Flag.Error);
}
if (src == null)
{
Debug.Log("Cannot blit with null src!", Debug.Flag.Error);
return;
}
var renderWindowSize = GetRenderSize();
bool isDefault = dst == null;
int width;
int height;
if (isDefault)
{
width = renderWindowSize.X;
height = renderWindowSize.Y;
}
else
{
width = dst.Width;
height = dst.Height;
}
unsafeBlitShader.SetVector2(Shader.GetShaderPropertyId("MainTex_TexelSize"), new Vector2(1.0f / width, 1.0f / height));
unsafeBlitShader.SetTexture(Shader.GetShaderPropertyId("MainTex"), src.TextureAttachments[srcTextureIndex]);
int results = unsafeBlitShader.AttachShaderForRendering();
if((results & 0b10) == 0b10)
{
GraphicsDebug.MaterialUpdateCount++;
}
if ((results & 0b1) == 0b1)
{
GraphicsDebug.UseProgramCount++;
}
if (isDefault)
{
//bind default framebuffer
GL.BindFramebuffer(FramebufferTarget.Framebuffer, 0);
GL.Viewport(0, 0, width, height);
}
else
{
//bind custom framebuffer
//force to draw only to a specified texture attachment
FrameBuffer.BindFramebuffer(dst);
GL.DrawBuffers(1, new DrawBuffersEnum[] { DrawBuffersEnum.ColorAttachment0 + dstColorAttachIndex });
}
GL.BindVertexArray(FullScreenQuad.VAO);
GL.BindBuffer(BufferTarget.ElementArrayBuffer, FullScreenQuad.EBO);
GraphicsDebug.DrawCount++;
GraphicsDebug.TotalVertices += FullScreenQuad.VertexCount;
GL.DrawElements(BeginMode.Triangles, FullScreenQuad.IndiciesCount, DrawElementsType.UnsignedInt, 0);
}
internal void EndBlitUnsafe(Shader shader)
{
Shader blitShader = shader ?? PassthroughShader;
if (!blitUnsafeFlag)
{
Debug.Log("EndBlitUnsafe already ended!", Debug.Flag.Error);
}
if(blitShader != unsafeBlitShader)
{
Debug.Log("EndBlitUnsafe blit shader mismatch!", Debug.Flag.Error);
}
blitUnsafeFlag = false;
}
List<RenderPass> renderPasses = new List<RenderPass>();
public void EnqueueRenderPass(RenderPass renderPass)
{
if (renderPass == null)
{
return;
}
renderPasses.Add(renderPass);
}
public void DequeueRenderPass(RenderPass renderPass)
{
if(renderPass == null)
{
return;
}
renderPasses.Remove(renderPass);
}
public T GetRenderPass<T>() where T : RenderPass
{
for (int i = 0; i < renderPasses.Count; i++)
{
if (renderPasses[i].GetType() == typeof(T))
{
return (T)renderPasses[i];
}
}
return null;
}
int ExecuteRenderPasses(int startingIndex, int renderQueueEnd)
{
int renderPassIndex;
for (int i = 0; i < MainFrameBuffer.TextureAttachments.Length; i++)
{
if (MainFrameBuffer.TextureAttachments[i].generateMipMaps)
{
GL.GenerateTextureMipmap(MainFrameBuffer.TextureAttachments[i].GlTextureID);
}
}
for (renderPassIndex = startingIndex; renderPassIndex < renderPasses.Count; renderPassIndex++)
{
if (renderPasses[renderPassIndex].Queue > (renderQueueEnd - 1))
{
return renderPassIndex;
}
PerfTimer.Start(renderPasses[renderPassIndex].Name);
renderPasses[renderPassIndex].Execute(MainFrameBuffer);
PerfTimer.Stop();
}
return renderPassIndex;
}
public void RenderSkyBox(Camera camera, Shader overrideShader = null)
{
if(camera.CameraMode == Camera.CameraType.Orthographic)
{
return;
}
PerfTimer.Start("RenderSkyBox");
//render skybox
GL.BindBuffer(BufferTarget.ElementArrayBuffer, BasicCube.EBO);
GL.BindVertexArray(BasicCube.VAO);
var mat = overrideShader == null ? SkyboxShader : overrideShader;
mat.SetMat4(Shader.GetShaderPropertyId("ModelMatrix"), Matrix4.CreateTranslation(camera.Transform.LocalPosition));
mat.AttachShaderForRendering();
GL.CullFace(CullFaceMode.Front);
GL.DrawElements(PrimitiveType.Triangles, BasicCube.IndiciesCount, DrawElementsType.UnsignedInt, 0);
GL.CullFace(CullFaceMode.Back);
GL.DepthMask(true);
GraphicsDebug.DrawCount++;
GraphicsDebug.TotalVertices += BasicCube.VertexCount;
GraphicsDebug.UseProgramCount++;
GraphicsDebug.MeshBindCount++;
PerfTimer.Stop();
}
private void DoRenderUpdate()
{
renderPasses.Sort();
float depthClearColor = ReverseDepth ? 0 : 1;
for (int cameraIndex = 0; cameraIndex < AllCameras.Count; cameraIndex++)
{
if (!AllCameras[cameraIndex].IsActiveAndEnabled)
{
continue;
}
RenderPass.CurrentRenderingCamera = AllCameras[cameraIndex];
SetupLights(AllCameras[cameraIndex]);
for (int i = 0; i < renderPasses.Count; i++)
{
renderPasses[i].FrameSetup(AllCameras[cameraIndex]);
}
GL.Disable(EnableCap.Blend);
//bind Main render texture RT
GL.BindFramebuffer(FramebufferTarget.Framebuffer, MainFrameBuffer.FrameBufferObject);
DrawBuffersEnum[] drawBuffers = new DrawBuffersEnum[MainFrameBuffer.TextureAttachments.Length];
int drawBufferCount = 0;
for (int i = 0; i < MainFrameBuffer.TextureAttachments.Length; i++)
{
if (Texture.IsDepthComponent(MainFrameBuffer.TextureAttachments[i].internalPixelFormat))
{
continue;
}
drawBuffers[i] = DrawBuffersEnum.ColorAttachment0 + drawBufferCount;
drawBufferCount++;
}
GL.DrawBuffers(drawBufferCount, drawBuffers);
GL.Viewport(0, 0, MainFrameBuffer.Width, MainFrameBuffer.Height);
GL.ClearDepth(depthClearColor);
GL.ClearColor(Color4.Magenta);
GL.Clear(ClearBufferMask.DepthBufferBit | ClearBufferMask.ColorBufferBit);
if (DepthPrepass == DepthPrePassMode.DepthOnly)
{
//render depth prepass
RenderScene(AllCameras[cameraIndex], DepthPrepassShader);
RenderSkyBox(AllCameras[cameraIndex], SkyboxDepthPrepassShader);
Blit(MainFrameBuffer, DepthTextureBuffer, true, null, 3, 0);
GL.Clear(ClearBufferMask.ColorBufferBit);
}
//prepass (Prepass -> Opaque - 1)
int renderPassIndex = ExecuteRenderPasses(0, (int)RenderQueue.AfterOpaques);
if (DepthPrepass == DepthPrePassMode.MotionVectors)
{
//Ensure motion vector render pass is enqueued!
Blit(MainFrameBuffer, DepthTextureBuffer, true, null, 3, 0);
GL.Clear(ClearBufferMask.ColorBufferBit);
}
//render Opaques
//TODO: move to render pass class
RenderScene(AllCameras[cameraIndex]);
RenderSkyBox(AllCameras[cameraIndex]);
//if no depth prepass, copy depth after running forward pass
if (DepthPrepass == DepthPrePassMode.None)
{
Blit(MainFrameBuffer, DepthTextureBuffer, true, null, 3, 0);
}
//Post opaque pass (Opaque -> Transparent - 1)
renderPassIndex = ExecuteRenderPasses(renderPassIndex, (int)RenderQueue.AfterTransparents);
//render Transparents
//Post transparent render pass (Transparent -> PostProcess - 1)
renderPassIndex = ExecuteRenderPasses(renderPassIndex, (int)RenderQueue.AfterPostProcessing);
//Post post processing (PostProcess -> End)
ExecuteRenderPasses(renderPassIndex, int.MaxValue);
if (GraphicsDebug.DrawAABB)
{
RenderBoundingBoxes(AllCameras[cameraIndex], MainFrameBuffer);
}
if (BlitFinalResultsToScreen)
{
//blit render buffer to screen
Blit(MainFrameBuffer, null, true, null);
}
//frame cleanup
for (int i = 0; i < renderPasses.Count; i++)
{
renderPasses[i].FrameCleanup();
}
}
}
private PointLightSSBO[] pointLightSSBOs = new PointLightSSBO[MAXPOINTLIGHTS];
private UBO<PointLightSSBO> PointLightBufferData;
void SetupLights(Camera camera)
{
PerfTimer.Start("SetupLights");
if(PointLightBufferData == null)
{
PointLightBufferData = new UBO<PointLightSSBO>(pointLightSSBOs, pointLightSSBOs.Length, 3);
}
List<(PointLight, int)> pointLights = new();
var lights = InternalGlobalScope<Light>.Values;
int pointLightShadowCount = 0;
bool didRenderDirectionalShadow = false;
bool noDirectionalLight = true;
for (int i = 0; i < lights.Count; i++)
{
switch (lights[i])
{
case DirectionalLight t0:
if (!lights[i].IsActiveAndEnabled)
{
Shader.SetGlobalVector3(Shader.GetShaderPropertyId("DirectionalLight.Color"), Vector3.Zero);
continue;
}
if (t0.HasShadows)
{
t0.RenderShadowMap(camera);
didRenderDirectionalShadow = true;
}
noDirectionalLight = false;
Shader.SetGlobalVector3(Shader.GetShaderPropertyId("DirectionalLight.Color"), t0.Color);
Shader.SetGlobalVector3(Shader.GetShaderPropertyId("DirectionalLight.Direction"), t0.Transform.Forward);
break;
case PointLight t0:
if (!lights[i].IsActiveAndEnabled)
{
continue;
}
pointLights.Add((t0, pointLightShadowCount));
if (t0.HasShadows)
{
t0.RenderShadowMap(camera);
Shader.SetGlobalTexture(Shader.GetShaderPropertyId("PointLightShadowMap[" + pointLightShadowCount + "]"), t0.GetShadowMapper().DepthCubemap);
pointLightShadowCount++;
}
break;
}
}
if (noDirectionalLight)
{
Shader.SetGlobalVector3(Shader.GetShaderPropertyId("DirectionalLight.Color"), Vector3.Zero);
Shader.SetGlobalVector3(Shader.GetShaderPropertyId("DirectionalLight.Direction"), Vector3.UnitZ);
}
if (!didRenderDirectionalShadow)
{
DirectionalShadowMap.SetShadowMapToWhite();
}
//point light frustum culling?
//render closer point lights first
pointLights.Sort((a, b) =>
{
var distance0 = (a.Item1.Transform.LocalPosition - camera.Transform.LocalPosition).LengthSquared;
var distance1 = (b.Item1.Transform.LocalPosition - camera.Transform.LocalPosition).LengthSquared;
if(distance0 < distance1)
{
return -1;
}
else
{
return 1;
}
});
for (int i = 0; i < MathF.Min(pointLights.Count, MAXPOINTLIGHTS); i++)
{
PointLight pointLight = pointLights[i].Item1;
unsafe
{
pointLightSSBOs[i].Position = new Vector4(pointLight.Transform.LocalPosition, 0);
pointLightSSBOs[i].Color = new Vector4(pointLight.Color, 0);
pointLightSSBOs[i].Constant = pointLight.AttenConstant;
pointLightSSBOs[i].Linear = pointLight.AttenLinear;
pointLightSSBOs[i].Exp = 1 - pointLight.AttenLinear;
pointLightSSBOs[i].Range = pointLight.Range;
pointLightSSBOs[i].HasShadows = pointLight.HasShadows ? 1 : 0;
}
if (pointLight.HasShadows)
{
pointLightSSBOs[i].ShadowFarPlane = pointLight.GetShadowMapper().FarPlane;
pointLightSSBOs[i].ShadowIndex = pointLights[i].Item2;
}
}
PointLightBufferData.UpdateData(pointLightSSBOs, pointLightSSBOs.Length);
Shader.SetGlobalInt(Shader.GetShaderPropertyId("PointLightCount"), (int)MathF.Min(pointLights.Count, MAXPOINTLIGHTS));
PerfTimer.Stop();
}
Renderer[] SortRenderersByMaterial(List<Renderer> renderers, int uniqueMaterials, Dictionary<Shader, int> caching)
{
Dictionary<Shader, int> materialIndex = caching;
List<Renderer>[] materials = new List<Renderer>[uniqueMaterials];
int materialCount;
int index;
for (int i = 0; i < renderers.Count; i++)
{
materialCount = materialIndex.Count;
var current = renderers[i];
if (!materialIndex.ContainsKey(current.Material))
{
materialIndex.Add(current.Material, materialCount);
var list = new List<Renderer>();
materials[materialCount] = list;
list.Add(current);
}
else
{
index = materialIndex[current.Material];
materials[index].Add(current);
}
}
index = 0;
var final = new Renderer[renderers.Count];