forked from space-wizards/RobustToolbox
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathClyde.cs
More file actions
591 lines (484 loc) · 21.8 KB
/
Copy pathClyde.cs
File metadata and controls
591 lines (484 loc) · 21.8 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
using System;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Threading;
using OpenToolkit;
using OpenToolkit.Graphics.OpenGL4;
using Robust.Client.GameObjects;
using Robust.Client.Input;
using Robust.Client.Map;
using Robust.Client.ResourceManagement;
using Robust.Client.UserInterface;
using Robust.Client.Utility;
using Robust.Shared;
using Robust.Shared.Configuration;
using Robust.Shared.ContentPack;
using Robust.Shared.GameObjects;
using Robust.Shared.Graphics;
using Robust.Shared.IoC;
using Robust.Shared.Localization;
using Robust.Shared.Log;
using Robust.Shared.Map;
using Robust.Shared.Maths;
using Robust.Shared.Profiling;
using Robust.Shared.Prototypes;
using Robust.Shared.Timing;
using Robust.Shared.Utility;
using TextureWrapMode = Robust.Shared.Graphics.TextureWrapMode;
namespace Robust.Client.Graphics.Clyde
{
/// <summary>
/// Responsible for most things rendering on OpenGL mode.
/// </summary>
internal sealed partial class Clyde : IClydeInternal, IPostInjectInit, IEntityEventSubscriber
{
[Dependency] private IClydeTileDefinitionManager _tileDefinitionManager = default!;
[Dependency] private ILightManager _lightManager = default!;
[Dependency] private ILogManager _logManager = default!;
[Dependency] private IOverlayManager _overlayManager = default!;
[Dependency] private IResourceCache _resourceCache = default!;
[Dependency] private IResourceManager _resManager = default!;
[Dependency] private IUserInterfaceManagerInternal _userInterfaceManager = default!;
[Dependency] private IEntitySystemManager _entitySystemManager = default!;
[Dependency] private IGameTiming _gameTiming = default!;
[Dependency] private IConfigurationManager _cfg = default!;
[Dependency] private ProfManager _prof = default!;
[Dependency] private IDependencyCollection _deps = default!;
[Dependency] private ILocalizationManager _loc = default!;
[Dependency] private IInputManager _inputManager = default!;
[Dependency] private ClientEntityManager _entityManager = default!;
[Dependency] private IPrototypeManager _proto = default!;
[Dependency] private IReloadManager _reloads = default!;
[Dependency] private LoadingScreenManager _loadingScreenManager = default!;
private GLUniformBuffer<ProjViewMatrices> ProjViewUBO = default!;
private GLUniformBuffer<UniformConstants> UniformConstantsUBO = default!;
private GLBuffer BatchVBO = default!;
private GLBuffer BatchEBO = default!;
private GLHandle BatchVAO;
// VBO to draw a single quad.
private GLBuffer QuadVBO = default!;
private GLHandle QuadVAO;
// VBO to blit to the window
// VAO is per-window and not stored (not necessary!)
private GLBuffer WindowVBO = default!;
private bool _drawingLoadingScreen = true;
private GLShaderProgram? _currentProgram;
private float _lightResolutionScale = 0.5f;
private int _maxLights = 2048;
private int _maxOccluders = 2048;
private int _maxShadowcastingLights = 128;
private bool _enableSoftShadows = true;
private bool _checkGLErrors;
private Thread? _gameThread;
private ISawmill _clydeSawmill = default!;
private ISawmill _sawmillOgl = default!;
private ISawmill _sawmillWin = default!;
private IBindingsContext _glBindingsContext = default!;
private bool _earlyGLInit;
private bool _threadWindowApi;
public bool IsInitialized { get; private set; }
public Clyde()
{
_currentBoundRenderTarget = default!;
_currentRenderTarget = default!;
SixLabors.ImageSharp.Configuration.Default.PreferContiguousImageBuffers = true;
}
public bool InitializePreWindowing()
{
_clydeSawmill = _logManager.GetSawmill("clyde");
_sawmillOgl = _logManager.GetSawmill("clyde.ogl");
_sawmillWin = _logManager.GetSawmill("clyde.win");
_reloads.Register("/Shaders", "*.swsl");
_reloads.Register("/Textures/Shaders", "*.swsl");
_reloads.Register("/Textures", "*.jpg");
_reloads.Register("/Textures", "*.jpeg");
_reloads.Register("/Textures", "*.png");
_reloads.Register("/Textures", "*.webp");
_reloads.OnChanged += OnChange;
_proto.PrototypesReloaded += OnProtoReload;
_cfg.OnValueChanged(CVars.DisplayOGLCheckErrors, b => _checkGLErrors = b, true);
_cfg.OnValueChanged(CVars.DisplayWindowMode, WindowModeChanged, true);
_cfg.OnValueChanged(CVars.LightResolutionScale, LightResolutionScaleChanged, true);
_cfg.OnValueChanged(CVars.MaxShadowcastingLights, MaxShadowcastingLightsChanged, true);
_cfg.OnValueChanged(CVars.LightSoftShadows, SoftShadowsChanged, true);
_cfg.OnValueChanged(CVars.MaxLightCount, MaxLightsChanged, true);
_cfg.OnValueChanged(CVars.MaxOccluderCount, MaxOccludersChanged, true);
_cfg.OnValueChanged(CVars.RenderTileEdges, RenderTileEdgesChanges, true);
// I can't be bothered to tear down and set these threads up in a cvar change handler.
// Windows and Linux can be trusted to not explode with threaded windowing,
// macOS cannot.
if (OperatingSystem.IsWindows() || OperatingSystem.IsLinux())
_cfg.OverrideDefault(CVars.DisplayThreadWindowApi, true);
#if MACOS
// Trust macOS to not need threaded window blitting.
// (threaded window blitting is a workaround to avoid having to frequently MakeCurrent() on Windows, as it is broken).
_cfg.OverrideDefault(CVars.DisplayThreadWindowBlit, false);
#endif
_threadWindowBlit = _cfg.GetCVar(CVars.DisplayThreadWindowBlit);
_threadWindowApi = _cfg.GetCVar(CVars.DisplayThreadWindowApi);
InitKeys();
return InitWindowing();
}
private void OnProtoReload(PrototypesReloadedEventArgs obj)
{
if (!obj.WasModified<ShaderPrototype>())
return;
foreach (var shader in obj.ByType[typeof(ShaderPrototype)].Modified.Keys)
{
_resourceCache.ReloadResource<ShaderSourceResource>(shader);
}
}
private void OnChange(ResPath obj)
{
if ((obj.TryRelativeTo(new ResPath("/Shaders"), out _) || obj.TryRelativeTo(new ResPath("/Textures/Shaders"), out _)) && obj.Extension == "swsl")
{
_resourceCache.ReloadResource<ShaderSourceResource>(obj);
}
if (obj.TryRelativeTo(new ResPath("/Textures"), out _) && !obj.TryRelativeTo(new ResPath("/Textures/Tiles"), out _))
{
if (obj.Extension == "jpg" || obj.Extension == "jpeg" || obj.Extension == "webp")
{
_resourceCache.ReloadResource<TextureResource>(obj);
}
if (obj.Extension == "png")
{
_resourceCache.ReloadResource<TextureResource>(obj);
}
}
}
public bool InitializePostWindowing()
{
_gameThread = Thread.CurrentThread;
InitSystems();
InitGLContextManager();
if (!InitMainWindowAndRenderer())
return false;
IsInitialized = true;
return true;
}
public bool SeparateWindowThread => _threadWindowApi;
public void EnterWindowLoop()
{
_windowing!.EnterWindowLoop();
}
public void TerminateWindowLoop()
{
_windowing!.TerminateWindowLoop();
}
public void FrameProcess(FrameEventArgs eventArgs)
{
if (!_threadWindowApi)
{
_windowing!.PollEvents();
}
_windowing?.FlushDispose();
FlushShaderInstanceDispose();
FlushRenderTargetDispose();
FlushTextureDispose();
FlushViewportDispose();
}
public void Ready()
{
_drawingLoadingScreen = false;
InitLighting();
}
public IClydeDebugInfo DebugInfo { get; private set; } = default!;
public IClydeDebugStats DebugStats => _debugStats;
public void PostInject()
{
// This cvar does not modify the actual GL version requested or anything,
// it overrides the version we detect to detect GL features.
RegisterBlockCVars();
}
public void RegisterGridEcsEvents()
{
_entityManager.EventBus.SubscribeEvent<TileChangedEvent>(EventSource.Local, this, _updateTileMapOnUpdate);
_entityManager.EventBus.SubscribeEvent<GridStartupEvent>(EventSource.Local, this, _updateOnGridCreated);
_entityManager.EventBus.SubscribeEvent<GridRemovalEvent>(EventSource.Local, this, _updateOnGridRemoved);
}
public void ShutdownGridEcsEvents()
{
_entityManager.EventBus.UnsubscribeEvent<TileChangedEvent>(EventSource.Local, this);
_entityManager.EventBus.UnsubscribeEvent<GridStartupEvent>(EventSource.Local, this);
_entityManager.EventBus.UnsubscribeEvent<GridRemovalEvent>(EventSource.Local, this);
}
private void GLInitBindings(bool gles)
{
_glBindingsContext = _glContext!.BindingsContext;
GL.LoadBindings(_glBindingsContext);
if (gles)
{
// On GLES we use some OES and KHR functions so make sure to initialize them.
OpenToolkit.Graphics.ES20.GL.LoadBindings(_glBindingsContext);
}
}
private void InitOpenGL()
{
_isGLES = _openGLVersion is RendererOpenGLVersion.GLES2 or RendererOpenGLVersion.GLES3;
_isGLES2 = _openGLVersion is RendererOpenGLVersion.GLES2;
_isCore = _openGLVersion is RendererOpenGLVersion.GL33;
GLInitBindings(_isGLES);
var vendor = GL.GetString(StringName.Vendor);
var renderer = GL.GetString(StringName.Renderer);
var version = GL.GetString(StringName.Version);
// GLES2 doesn't allow you to query major/minor version. Seriously.
var major = _openGLVersion == RendererOpenGLVersion.GLES2 ? 2 : GL.GetInteger(GetPName.MajorVersion);
var minor = _openGLVersion == RendererOpenGLVersion.GLES2 ? 0 :GL.GetInteger(GetPName.MinorVersion);
_sawmillOgl.Debug("OpenGL Vendor: {0}", vendor);
_sawmillOgl.Debug("OpenGL Renderer: {0}", renderer);
_sawmillOgl.Debug("OpenGL Version: {0}", version);
var overrideVersion = ParseGLOverrideVersion();
if (overrideVersion != null)
{
(major, minor) = overrideVersion.Value;
_sawmillOgl.Debug("OVERRIDING detected GL version to: {0}.{1}", major, minor);
}
DetectOpenGLFeatures(major, minor);
SetupDebugCallback();
LoadVendorSettings(vendor, renderer, version);
var glVersion = new OpenGLVersion((byte) major, (byte) minor, _isGLES, _isCore);
DebugInfo = new ClydeDebugInfo(
glVersion,
renderer,
vendor,
version,
overrideVersion != null,
_windowing!.GetDescription());
IsBlending = true;
if (_hasGLSrgb && !_isGLES)
{
GL.Enable(EnableCap.FramebufferSrgb);
CheckGlError();
}
if (_hasGLPrimitiveRestart)
{
GL.Enable(EnableCap.PrimitiveRestart);
CheckGlError();
GL.PrimitiveRestartIndex(PrimitiveRestartIndex);
CheckGlError();
}
if (_hasGLPrimitiveRestartFixedIndex)
{
GL.Enable(EnableCap.PrimitiveRestartFixedIndex);
CheckGlError();
}
if (!HasGLAnyVertexArrayObjects)
{
_sawmillOgl.Warning("NO VERTEX ARRAY OBJECTS! Things will probably go terribly, terribly wrong (no fallback path yet)");
}
ResetBlendFunc();
CheckGlError();
// Primitive Restart's presence or lack thereof changes the amount of required memory.
InitRenderingBatchBuffers();
_sawmillOgl.Debug("Loading stock textures...");
LoadStockTextures();
_sawmillOgl.Debug("Loading stock shaders...");
LoadStockShaders();
_sawmillOgl.Debug("Creating various GL objects...");
CreateMiscGLObjects();
_sawmillOgl.Debug("Setting up RenderHandle...");
_renderHandle = new RenderHandle(this, _entityManager);
}
private (int major, int minor)? ParseGLOverrideVersion()
{
var overrideGLVersion = _cfg.GetCVar(CVars.DisplayOGLOverrideVersion);
if (string.IsNullOrEmpty(overrideGLVersion))
{
return null;
}
var split = overrideGLVersion.Split(".");
if (split.Length != 2)
{
_sawmillOgl.Warning("display.ogl_override_version is in invalid format");
return null;
}
if (!int.TryParse(split[0], NumberStyles.Integer, CultureInfo.InvariantCulture, out var major)
|| !int.TryParse(split[1], NumberStyles.Integer, CultureInfo.InvariantCulture, out var minor))
{
_sawmillOgl.Warning("display.ogl_override_version is in invalid format");
return null;
}
return (major, minor);
}
private unsafe void CreateMiscGLObjects()
{
// Quad drawing.
{
Span<Vertex2D> quadVertices = stackalloc[]
{
new Vertex2D(1, 0, 1, 1, Color.White),
new Vertex2D(0, 0, 0, 1, Color.White),
new Vertex2D(1, 1, 1, 0, Color.White),
new Vertex2D(0, 1, 0, 0, Color.White)
};
QuadVBO = new GLBuffer<Vertex2D>(this, BufferTarget.ArrayBuffer, BufferUsageHint.StaticDraw,
quadVertices,
nameof(QuadVBO));
QuadVAO = MakeQuadVao();
CheckGlError();
}
// Window VBO
{
Span<Vertex2D> winVertices = stackalloc[]
{
new Vertex2D(-1, 1, 0, 1, Color.White),
new Vertex2D(-1, -1, 0, 0, Color.White),
new Vertex2D(1, 1, 1, 1, Color.White),
new Vertex2D(1, -1, 1, 0, Color.White),
};
WindowVBO = new GLBuffer<Vertex2D>(
this,
BufferTarget.ArrayBuffer,
BufferUsageHint.StaticDraw,
winVertices,
nameof(WindowVBO));
CheckGlError();
}
// Batch rendering
{
BatchVBO = new GLBuffer(this, BufferTarget.ArrayBuffer, BufferUsageHint.DynamicDraw,
sizeof(Vertex2D) * BatchVertexData.Length, nameof(BatchVBO));
BatchVAO = new GLHandle(GenVertexArray());
BindVertexArray(BatchVAO.Handle);
ObjectLabelMaybe(ObjectLabelIdentifier.VertexArray, BatchVAO, nameof(BatchVAO));
SetupVAOLayout();
CheckGlError();
BatchEBO = new GLBuffer(this, BufferTarget.ElementArrayBuffer, BufferUsageHint.DynamicDraw,
sizeof(ushort) * BatchIndexData.Length, nameof(BatchEBO));
}
ProjViewUBO = new GLUniformBuffer<ProjViewMatrices>(this, BindingIndexProjView, nameof(ProjViewUBO));
UniformConstantsUBO = new GLUniformBuffer<UniformConstants>(this, BindingIndexUniformConstants, nameof(UniformConstantsUBO));
screenBufferHandle = new GLHandle(GL.GenTexture());
GL.BindTexture(TextureTarget.Texture2D, screenBufferHandle.Handle);
ApplySampleParameters(new TextureSampleParameters() { Filter = false, WrapMode = TextureWrapMode.MirroredRepeat});
// TODO: This is atrocious and broken and awful why did I merge this
ScreenBufferTexture = GenTexture(screenBufferHandle, (1920, 1080), true, null, TexturePixelType.Rgba32);
}
private GLHandle MakeQuadVao()
{
var vao = new GLHandle(GenVertexArray());
BindVertexArray(vao.Handle);
ObjectLabelMaybe(ObjectLabelIdentifier.VertexArray, vao, nameof(QuadVAO));
GL.BindBuffer(BufferTarget.ArrayBuffer, QuadVBO.ObjectHandle);
SetupVAOLayout();
return vao;
}
[Conditional("DEBUG")]
private unsafe void SetupDebugCallback()
{
if (!_hasGLKhrDebug)
{
_sawmillOgl.Debug("KHR_debug not present, OpenGL debug logging not enabled.");
return;
}
GL.Enable(EnableCap.DebugOutput);
GL.Enable(EnableCap.DebugOutputSynchronous);
_debugMessageCallbackInstance ??= DebugMessageCallback;
// OpenTK seemed to have trouble marshalling the delegate so do it manually.
var procName = _isGLKhrDebugESExtension ? "glDebugMessageCallbackKHR" : "glDebugMessageCallback";
var glDebugMessageCallback = (delegate* unmanaged[Stdcall] <nint, nint, void>) LoadGLProc(procName);
var funcPtr = Marshal.GetFunctionPointerForDelegate(_debugMessageCallbackInstance);
glDebugMessageCallback(funcPtr, new IntPtr(0x3005));
}
private void DebugMessageCallback(DebugSource source, DebugType type, int id, DebugSeverity severity,
int length, IntPtr message, IntPtr userParam)
{
var category = type switch
{
DebugType.DebugTypePerformance => "ogl.debug.performance",
DebugType.DebugTypeOther => "ogl.debug.other",
DebugType.DebugTypeError => "ogl.debug.error",
DebugType.DebugTypeDeprecatedBehavior => "ogl.debug.deprecated",
DebugType.DebugTypeUndefinedBehavior => "ogl.debug.ub",
DebugType.DebugTypePortability => "ogl.debug.portability",
DebugType.DebugTypeMarker or DebugType.DebugTypePushGroup or DebugType.DebugTypePopGroup =>
// These are inserted by our own code so I imagine they're not necessary to log?
null,
_ => throw new ArgumentOutOfRangeException(nameof(type), type, null)
};
if (category == null)
return;
var sawmill = _logManager.GetSawmill(category);
var level = severity switch
{
DebugSeverity.DontCare => LogLevel.Info,
DebugSeverity.DebugSeverityNotification => LogLevel.Info,
DebugSeverity.DebugSeverityHigh => LogLevel.Error,
DebugSeverity.DebugSeverityMedium => LogLevel.Error,
DebugSeverity.DebugSeverityLow => LogLevel.Warning,
_ => throw new ArgumentOutOfRangeException(nameof(severity), severity, null)
};
if (!sawmill.IsLogLevelEnabled(level))
return;
sawmill.Log(level, "{0}: {1}", source, Marshal.PtrToStringAnsi(message, length));
}
private static DebugProc? _debugMessageCallbackInstance;
[Conditional("DEBUG")]
private void ObjectLabelMaybe(ObjectLabelIdentifier identifier, uint name, string? label)
{
if (label == null)
{
return;
}
if (!_hasGLKhrDebug || !_glDebuggerPresent)
return;
if (_isGLKhrDebugESExtension)
{
GL.Khr.ObjectLabel((ObjectIdentifier) identifier, name, label.Length, label);
}
else
{
GL.ObjectLabel(identifier, name, label.Length, label);
}
}
[Conditional("DEBUG")]
private void ObjectLabelMaybe(ObjectLabelIdentifier identifier, GLHandle name, string? label)
{
ObjectLabelMaybe(identifier, name.Handle, label);
}
private PopDebugGroup DebugGroup(string group)
{
PushDebugGroupMaybe(group);
return new PopDebugGroup(this);
}
[Conditional("DEBUG")]
private void PushDebugGroupMaybe(string group)
{
// ANGLE spams console log messages when using debug groups, so let's only use them if we're debugging GL.
if (!_hasGLKhrDebug || !_glDebuggerPresent)
return;
if (_isGLKhrDebugESExtension)
{
GL.Khr.PushDebugGroup((DebugSource) DebugSourceExternal.DebugSourceApplication, 0, group.Length, group);
}
else
{
GL.PushDebugGroup(DebugSourceExternal.DebugSourceApplication, 0, group.Length, group);
}
}
[Conditional("DEBUG")]
private void PopDebugGroupMaybe()
{
if (!_hasGLKhrDebug || !_glDebuggerPresent)
return;
if (_isGLKhrDebugESExtension)
{
GL.Khr.PopDebugGroup();
}
else
{
GL.PopDebugGroup();
}
}
public void Shutdown()
{
_glContext?.Shutdown();
ShutdownWindowing();
}
private bool IsMainThread()
{
return Thread.CurrentThread == _gameThread;
}
}
}