forked from crosire/reshade
-
Notifications
You must be signed in to change notification settings - Fork 0
/
runtime_gl.cpp
1459 lines (1247 loc) · 48.9 KB
/
runtime_gl.cpp
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
/*
* Copyright (C) 2014 Patrick Mours. All rights reserved.
* License: https://github.com/crosire/reshade#license
*/
#include "dll_log.hpp"
#include "runtime_gl.hpp"
#include "runtime_config.hpp"
#include "runtime_objects.hpp"
#include <imgui.h>
namespace reshade::opengl
{
struct opengl_tex_data
{
GLuint id[2] = {};
GLenum internal_format = GL_NONE;
};
struct opengl_pass_data
{
GLuint fbo = 0;
GLuint program = 0;
GLenum blend_eq_color = GL_NONE;
GLenum blend_eq_alpha = GL_NONE;
GLenum blend_src = GL_NONE;
GLenum blend_src_alpha = GL_NONE;
GLenum blend_dest = GL_NONE;
GLenum blend_dest_alpha = GL_NONE;
GLenum stencil_func = GL_NONE;
GLenum stencil_op_fail = GL_NONE;
GLenum stencil_op_z_fail = GL_NONE;
GLenum stencil_op_z_pass = GL_NONE;
GLenum draw_targets[8] = {};
GLuint draw_textures[8] = {};
};
struct opengl_sampler_data
{
GLuint id;
opengl_tex_data *texture;
bool is_srgb;
bool has_mipmaps;
};
struct opengl_storage_data
{
opengl_tex_data *texture;
};
struct opengl_technique_data
{
GLuint query = 0;
bool query_in_flight = false;
std::vector<opengl_pass_data> passes;
std::vector<opengl_sampler_data> samplers;
std::vector<opengl_storage_data> storages;
};
}
reshade::opengl::runtime_gl::runtime_gl()
{
GLint major = 0, minor = 0;
glGetIntegerv(GL_MAJOR_VERSION, &major);
glGetIntegerv(GL_MINOR_VERSION, &minor);
_renderer_id = 0x10000 | (major << 12) | (minor << 8);
const GLubyte *const name = glGetString(GL_RENDERER);
const GLubyte *const version = glGetString(GL_VERSION);
LOG(INFO) << "Running on " << name << " using OpenGL " << version;
// Query vendor and device ID from Windows assuming we are running on the primary display device
// This is done because the information reported by OpenGL is not always reflecting the actual rendering device (e.g. on NVIDIA Optimus laptops)
DISPLAY_DEVICEA dd = { sizeof(dd) };
for (DWORD i = 0; EnumDisplayDevicesA(nullptr, i, &dd, 0) != FALSE; ++i)
{
if ((dd.StateFlags & DISPLAY_DEVICE_PRIMARY_DEVICE) != 0)
{
std::sscanf(dd.DeviceID, "PCI\\VEN_%x&DEV_%x", &_vendor_id, &_device_id);
break;
}
}
#if RESHADE_GUI && RESHADE_DEPTH
subscribe_to_ui("OpenGL", [this]() { draw_depth_debug_menu(); });
#endif
subscribe_to_load_config([this](const ini_file &config) {
// Reserve a fixed amount of texture names by default to work around issues in old OpenGL games
// This hopefully should not affect performance much in other games
auto num_reserve_texture_names = 512u;
config.get("OPENGL", "ReserveTextureNames", num_reserve_texture_names);
_reserved_texture_names.resize(num_reserve_texture_names);
#if RESHADE_DEPTH
auto force_default_depth_override = false;
config.get("OPENGL", "ForceMainDepthBuffer", force_default_depth_override);
config.get("OPENGL", "UseAspectRatioHeuristics", _use_aspect_ratio_heuristics);
if (force_default_depth_override)
_depth_source_override = 0; // Zero has a special meaning and corresponds to the default depth buffer
});
subscribe_to_save_config([this](ini_file &config) {
config.set("OPENGL", "ForceMainDepthBuffer", _depth_source_override == 0);
config.set("OPENGL", "UseAspectRatioHeuristics", _use_aspect_ratio_heuristics);
#endif
});
#ifndef NDEBUG
glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS_ARB);
glDebugMessageCallback([](unsigned int /*source*/, unsigned int type, unsigned int /*id*/, unsigned int /*severity*/, int /*length*/, const char *message, const void */*userParam*/) {
if (type == GL_DEBUG_TYPE_ERROR || type == GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR)
OutputDebugStringA(message);
}, nullptr);
#endif
}
bool reshade::opengl::runtime_gl::on_init(HWND hwnd, unsigned int width, unsigned int height)
{
RECT window_rect = {};
GetClientRect(hwnd, &window_rect);
const HDC hdc = GetDC(hwnd);
PIXELFORMATDESCRIPTOR pfd = { sizeof(pfd) };
DescribePixelFormat(hdc, GetPixelFormat(hdc), sizeof(pfd), &pfd);
_width = width;
_height = height;
_window_width = window_rect.right;
_window_height = window_rect.bottom;
_color_bit_depth = pfd.cRedBits;
switch (pfd.cDepthBits)
{
default:
case 0: _default_depth_format = GL_NONE; // No depth in this pixel format
break;
case 16: _default_depth_format = GL_DEPTH_COMPONENT16;
break;
case 24: _default_depth_format = pfd.cStencilBits ? GL_DEPTH24_STENCIL8 : GL_DEPTH_COMPONENT24;
break;
case 32: _default_depth_format = pfd.cStencilBits ? GL_DEPTH32F_STENCIL8 : GL_DEPTH_COMPONENT32;
break;
}
// Initialize default frame buffer information
_buffer_detection.reset(_width, _height, _default_depth_format);
// Capture and later restore so that the resource creation code below does not affect the application state
_app_state.capture();
// Some games (like Hot Wheels Velocity X) use fixed texture names, which can clash with the ones ReShade generates below, since most implementations will return values linearly
// Reserve a configurable range of names for those games to work around this
glGenTextures(GLsizei(_reserved_texture_names.size()), _reserved_texture_names.data());
glGenBuffers(NUM_BUF, _buf);
glGenTextures(NUM_TEX, _tex);
glGenVertexArrays(NUM_VAO, _vao);
glGenFramebuffers(NUM_FBO, _fbo);
glGenRenderbuffers(NUM_RBO, _rbo);
glBindTexture(GL_TEXTURE_2D, _tex[TEX_BACK]);
glTexStorage2D(GL_TEXTURE_2D, 1, GL_RGBA8, _width, _height);
glTextureView(_tex[TEX_BACK_SRGB], GL_TEXTURE_2D, _tex[TEX_BACK], GL_SRGB8_ALPHA8, 0, 1, 0, 1);
glBindRenderbuffer(GL_RENDERBUFFER, _rbo[RBO_COLOR]);
glRenderbufferStorage(GL_RENDERBUFFER, GL_SRGB8_ALPHA8, _width, _height);
glBindRenderbuffer(GL_RENDERBUFFER, _rbo[RBO_STENCIL]);
// As of OpenGL 4.3 support for GL_STENCIL_INDEX8 is a requirement for render buffers
glRenderbufferStorage(GL_RENDERBUFFER, GL_STENCIL_INDEX8, _width, _height);
glBindFramebuffer(GL_FRAMEBUFFER, _fbo[FBO_BACK]);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, _rbo[RBO_COLOR]);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, _rbo[RBO_STENCIL]);
assert(glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE);
glBindFramebuffer(GL_FRAMEBUFFER, _fbo[FBO_BLIT]);
glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, _tex[TEX_BACK_SRGB], 0);
assert(glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE);
#if RESHADE_DEPTH
// Initialize depth texture and FBO by assuming they refer to the default frame buffer
_has_depth_texture = _default_depth_format != GL_NONE;
if (_has_depth_texture)
{
_copy_depth_source = true;
_depth_source_width = _width;
_depth_source_height = _height;
_depth_source_format = _default_depth_format;
glBindTexture(GL_TEXTURE_2D, _tex[TEX_DEPTH]);
glTexStorage2D(GL_TEXTURE_2D, 1, _depth_source_format, _depth_source_width, _depth_source_height);
glBindFramebuffer(GL_FRAMEBUFFER, _fbo[FBO_DEPTH_DEST]);
glFramebufferTexture(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, _tex[TEX_DEPTH], 0);
assert(glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE);
}
#endif
#if RESHADE_GUI
init_imgui_resources();
#endif
_app_state.apply();
return runtime::on_init(hwnd);
}
void reshade::opengl::runtime_gl::on_reset()
{
runtime::on_reset();
glDeleteBuffers(NUM_BUF, _buf);
glDeleteTextures(NUM_TEX, _tex);
glDeleteTextures(GLsizei(_reserved_texture_names.size()), _reserved_texture_names.data());
glDeleteVertexArrays(NUM_VAO, _vao);
glDeleteFramebuffers(NUM_FBO, _fbo);
glDeleteRenderbuffers(NUM_RBO, _rbo);
std::memset(_buf, 0, sizeof(_vao));
std::memset(_tex, 0, sizeof(_tex));
std::memset(_vao, 0, sizeof(_vao));
std::memset(_fbo, 0, sizeof(_fbo));
std::memset(_rbo, 0, sizeof(_rbo));
#if RESHADE_GUI
glDeleteProgram(_imgui.program);
_imgui.program = 0;
#endif
#if RESHADE_DEPTH
_depth_source = 0;
_depth_source_width = 0;
_depth_source_height = 0;
_depth_source_format = 0;
_depth_source_override = std::numeric_limits<GLuint>::max();
_has_depth_texture = false;
_copy_depth_source = false;
#endif
}
void reshade::opengl::runtime_gl::on_present()
{
if (!_is_initialized)
return;
_vertices = _buffer_detection.total_vertices();
_drawcalls = _buffer_detection.total_drawcalls();
_app_state.capture();
#if RESHADE_DEPTH
update_depth_texture_bindings(_has_high_network_activity ? buffer_detection::depthstencil_info { 0 } :
_buffer_detection.find_best_depth_texture(_use_aspect_ratio_heuristics ? _width : 0, _height, _depth_source_override));
#endif
// Copy back buffer to RBO
glDisable(GL_SCISSOR_TEST);
glDisable(GL_FRAMEBUFFER_SRGB);
glBindFramebuffer(GL_READ_FRAMEBUFFER, 0);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, _fbo[FBO_BACK]);
glReadBuffer(GL_BACK);
glDrawBuffer(GL_COLOR_ATTACHMENT0);
glBlitFramebuffer(0, 0, _width, _height, 0, 0, _width, _height, GL_COLOR_BUFFER_BIT, GL_NEAREST);
_current_fbo = _fbo[FBO_BACK];
#if RESHADE_DEPTH
// Copy depth from FBO to depth texture
if (_copy_depth_source)
{
glBindFramebuffer(GL_READ_FRAMEBUFFER, _depth_source == 0 ? 0 : _fbo[FBO_DEPTH_SRC]);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, _fbo[FBO_DEPTH_DEST]);
glBlitFramebuffer(0, 0, _depth_source_width, _depth_source_height, 0, 0, _depth_source_width, _depth_source_height, GL_DEPTH_BUFFER_BIT, GL_NEAREST);
}
#endif
// Set clip space to something consistent
if (gl3wProcs.gl.ClipControl != nullptr)
glClipControl(GL_LOWER_LEFT, GL_ZERO_TO_ONE);
update_and_render_effects();
// Copy results from RBO to back buffer
glDisable(GL_SCISSOR_TEST);
glDisable(GL_FRAMEBUFFER_SRGB);
glBindFramebuffer(GL_READ_FRAMEBUFFER, _fbo[FBO_BACK]);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
glReadBuffer(GL_COLOR_ATTACHMENT0);
glDrawBuffer(GL_BACK);
glBlitFramebuffer(0, 0, _width, _height, 0, 0, _width, _height, GL_COLOR_BUFFER_BIT, GL_NEAREST);
_current_fbo = 0;
runtime::on_present();
_buffer_detection.reset(_width, _height, _default_depth_format);
// Apply previous state from application
_app_state.apply();
}
bool reshade::opengl::runtime_gl::capture_screenshot(uint8_t *buffer) const
{
assert(_app_state.has_state);
glBindFramebuffer(GL_READ_FRAMEBUFFER, _current_fbo);
glReadBuffer(_current_fbo == 0 ? GL_BACK : GL_COLOR_ATTACHMENT0);
glReadPixels(0, 0, GLsizei(_width), GLsizei(_height), GL_RGBA, GL_UNSIGNED_BYTE, buffer);
// Flip image horizontally
for (unsigned int y = 0, pitch = _width * 4; y * 2 < _height; ++y)
{
const auto i1 = y * pitch;
const auto i2 = (_height - 1 - y) * pitch;
for (unsigned int x = 0; x < pitch; x += 4)
{
std::swap(buffer[i1 + x + 0], buffer[i2 + x + 0]);
std::swap(buffer[i1 + x + 1], buffer[i2 + x + 1]);
std::swap(buffer[i1 + x + 2], buffer[i2 + x + 2]);
std::swap(buffer[i1 + x + 3], buffer[i2 + x + 3]);
}
}
return true;
}
bool reshade::opengl::runtime_gl::init_effect(size_t index)
{
assert(_app_state.has_state); // Make sure all binds below are reset later when application state is restored
effect &effect = _effects[index];
// Add specialization constant defines to source code
std::vector<GLuint> spec_data;
std::vector<GLuint> spec_constants;
if (!effect.module.spirv.empty())
{
for (const reshadefx::uniform_info &constant : effect.module.spec_constants)
{
const GLuint id = static_cast<GLuint>(spec_constants.size());
spec_data.push_back(constant.initializer_value.as_uint[0]);
spec_constants.push_back(id);
}
}
// Compile all entry points
std::unordered_map<std::string, GLuint> entry_points;
for (const reshadefx::entry_point &entry_point : effect.module.entry_points)
{
GLuint shader_type = GL_NONE;
switch (entry_point.type)
{
case reshadefx::shader_type::vs:
shader_type = GL_VERTEX_SHADER;
break;
case reshadefx::shader_type::ps:
shader_type = GL_FRAGMENT_SHADER;
break;
case reshadefx::shader_type::cs:
shader_type = GL_COMPUTE_SHADER;
break;
}
GLuint shader_object = glCreateShader(shader_type);
entry_points[entry_point.name] = shader_object;
if (!effect.module.spirv.empty())
{
assert(_renderer_id >= 0x14600); // Core since OpenGL 4.6 (see https://www.khronos.org/opengl/wiki/SPIR-V)
assert(gl3wProcs.gl.ShaderBinary != nullptr && gl3wProcs.gl.SpecializeShader != nullptr);
glShaderBinary(1, &shader_object, GL_SHADER_BINARY_FORMAT_SPIR_V, effect.module.spirv.data(), static_cast<GLsizei>(effect.module.spirv.size() * sizeof(uint32_t)));
glSpecializeShader(shader_object, entry_point.name.c_str(), GLuint(spec_constants.size()), spec_constants.data(), spec_data.data());
}
else
{
std::string defines = "#version 430\n";
defines += "#define ENTRY_POINT_" + entry_point.name + " 1\n";
if (entry_point.type == reshadefx::shader_type::vs)
{
// OpenGL does not allow using 'discard' in the vertex shader profile
defines += "#define discard\n";
// 'dFdx', 'dFdx' and 'fwidth' too are only available in fragment shaders
defines += "#define dFdx(x) x\n";
defines += "#define dFdy(y) y\n";
defines += "#define fwidth(p) p\n";
}
if (entry_point.type != reshadefx::shader_type::cs)
{
// OpenGL does not allow using 'shared' in vertex/fragment shader profile
defines += "#define shared\n";
defines += "#define atomicAdd(a, b) a\n";
defines += "#define atomicAnd(a, b) a\n";
defines += "#define atomicOr(a, b) a\n";
defines += "#define atomicXor(a, b) a\n";
defines += "#define atomicMin(a, b) a\n";
defines += "#define atomicMax(a, b) a\n";
defines += "#define atomicExchange(a, b) a\n";
defines += "#define atomicCompSwap(a, b, c) a\n";
// Barrier intrinsics are only available in compute shaders
defines += "#define barrier()\n";
defines += "#define memoryBarrier()\n";
defines += "#define groupMemoryBarrier()\n";
}
defines += "#line 1 0\n"; // Reset line number, so it matches what is shown when viewing the generated code
defines += effect.preamble;
GLsizei lengths[] = { static_cast<GLsizei>(defines.size()), static_cast<GLsizei>(effect.module.hlsl.size()) };
const GLchar *sources[] = { defines.c_str(), effect.module.hlsl.c_str() };
glShaderSource(shader_object, 2, sources, lengths);
glCompileShader(shader_object);
}
GLint status = GL_FALSE;
glGetShaderiv(shader_object, GL_COMPILE_STATUS, &status);
if (GL_FALSE == status)
{
GLint log_size = 0;
glGetShaderiv(shader_object, GL_INFO_LOG_LENGTH, &log_size);
std::vector<char> log(log_size);
glGetShaderInfoLog(shader_object, log_size, nullptr, log.data());
effect.errors += log.data();
for (auto &it : entry_points)
glDeleteShader(it.second);
// No need to setup resources if any of the shaders failed to compile
return false;
}
}
if (index >= _effect_ubos.size())
_effect_ubos.resize(index + 1);
if (!effect.uniform_data_storage.empty())
{
GLuint &ubo = _effect_ubos[index];
glGenBuffers(1, &ubo);
glBindBuffer(GL_UNIFORM_BUFFER, ubo);
glBufferData(GL_UNIFORM_BUFFER, effect.uniform_data_storage.size(), effect.uniform_data_storage.data(), GL_DYNAMIC_DRAW);
}
bool success = true;
opengl_technique_data technique_init;
assert(effect.module.num_texture_bindings == 0);
technique_init.samplers.resize(effect.module.num_sampler_bindings);
technique_init.storages.resize(effect.module.num_storage_bindings);
for (const reshadefx::sampler_info &info : effect.module.samplers)
{
const texture &texture = look_up_texture_by_name(info.texture_name);
// Hash sampler state to avoid duplicated sampler objects
size_t hash = 2166136261;
hash = (hash * 16777619) ^ static_cast<uint32_t>(info.address_u);
hash = (hash * 16777619) ^ static_cast<uint32_t>(info.address_v);
hash = (hash * 16777619) ^ static_cast<uint32_t>(info.address_w);
hash = (hash * 16777619) ^ static_cast<uint32_t>(info.filter);
hash = (hash * 16777619) ^ reinterpret_cast<const uint32_t &>(info.lod_bias);
hash = (hash * 16777619) ^ reinterpret_cast<const uint32_t &>(info.min_lod);
hash = (hash * 16777619) ^ reinterpret_cast<const uint32_t &>(info.max_lod);
std::unordered_map<size_t, GLuint>::iterator it = _effect_sampler_states.find(hash);
if (it == _effect_sampler_states.end())
{
GLenum min_filter = GL_NONE, mag_filter = GL_NONE;
switch (info.filter)
{
case reshadefx::texture_filter::min_mag_mip_point:
min_filter = GL_NEAREST_MIPMAP_NEAREST;
mag_filter = GL_NEAREST;
break;
case reshadefx::texture_filter::min_mag_point_mip_linear:
min_filter = GL_NEAREST_MIPMAP_LINEAR;
mag_filter = GL_NEAREST;
break;
case reshadefx::texture_filter::min_point_mag_linear_mip_point:
min_filter = GL_NEAREST_MIPMAP_NEAREST;
mag_filter = GL_LINEAR;
break;
case reshadefx::texture_filter::min_point_mag_mip_linear:
min_filter = GL_NEAREST_MIPMAP_LINEAR;
mag_filter = GL_LINEAR;
break;
case reshadefx::texture_filter::min_linear_mag_mip_point:
min_filter = GL_LINEAR_MIPMAP_NEAREST;
mag_filter = GL_NEAREST;
break;
case reshadefx::texture_filter::min_linear_mag_point_mip_linear:
min_filter = GL_LINEAR_MIPMAP_LINEAR;
mag_filter = GL_NEAREST;
break;
case reshadefx::texture_filter::min_mag_linear_mip_point:
min_filter = GL_LINEAR_MIPMAP_NEAREST;
mag_filter = GL_LINEAR;
break;
case reshadefx::texture_filter::min_mag_mip_linear:
min_filter = GL_LINEAR_MIPMAP_LINEAR;
mag_filter = GL_LINEAR;
break;
}
const auto convert_address_mode = [](reshadefx::texture_address_mode value) {
switch (value)
{
case reshadefx::texture_address_mode::wrap:
return GL_REPEAT;
case reshadefx::texture_address_mode::mirror:
return GL_MIRRORED_REPEAT;
case reshadefx::texture_address_mode::clamp:
return GL_CLAMP_TO_EDGE;
case reshadefx::texture_address_mode::border:
return GL_CLAMP_TO_BORDER;
default:
return GL_NONE;
}
};
GLuint sampler_id = 0;
glGenSamplers(1, &sampler_id);
glSamplerParameteri(sampler_id, GL_TEXTURE_WRAP_S, convert_address_mode(info.address_u));
glSamplerParameteri(sampler_id, GL_TEXTURE_WRAP_T, convert_address_mode(info.address_v));
glSamplerParameteri(sampler_id, GL_TEXTURE_WRAP_R, convert_address_mode(info.address_w));
glSamplerParameteri(sampler_id, GL_TEXTURE_MAG_FILTER, mag_filter);
glSamplerParameteri(sampler_id, GL_TEXTURE_MIN_FILTER, min_filter);
glSamplerParameterf(sampler_id, GL_TEXTURE_LOD_BIAS, info.lod_bias);
glSamplerParameterf(sampler_id, GL_TEXTURE_MIN_LOD, info.min_lod);
glSamplerParameterf(sampler_id, GL_TEXTURE_MAX_LOD, info.max_lod);
it = _effect_sampler_states.emplace(hash, sampler_id).first;
}
opengl_sampler_data &sampler_data = technique_init.samplers[info.binding];
sampler_data.id = it->second;
sampler_data.texture = static_cast<opengl_tex_data *>(texture.impl);
sampler_data.is_srgb = info.srgb;
sampler_data.has_mipmaps = texture.levels > 1;
}
for (const reshadefx::storage_info &info : effect.module.storages)
{
const texture &texture = look_up_texture_by_name(info.texture_name);
opengl_storage_data &storage_data = technique_init.storages[info.binding];
storage_data.texture = static_cast<opengl_tex_data *>(texture.impl);
}
for (technique &technique : _techniques)
{
if (technique.impl != nullptr || technique.effect_index != index)
continue;
// Copy construct new technique implementation instead of move because effect may contain multiple techniques
auto impl = new opengl_technique_data(technique_init);
technique.impl = impl;
glGenQueries(1, &impl->query);
impl->passes.resize(technique.passes.size());
for (size_t pass_index = 0; pass_index < technique.passes.size(); ++pass_index)
{
opengl_pass_data &pass_data = impl->passes[pass_index];
reshadefx::pass_info &pass_info = technique.passes[pass_index];
pass_data.program = glCreateProgram();
if (!pass_info.cs_entry_point.empty())
{
const GLuint cs_shader_id = entry_points.at(pass_info.cs_entry_point);
glAttachShader(pass_data.program, cs_shader_id);
glLinkProgram(pass_data.program);
glDetachShader(pass_data.program, cs_shader_id);
}
else
{
// Link program from input shaders
const GLuint vs_shader_id = entry_points.at(pass_info.vs_entry_point);
const GLuint fs_shader_id = entry_points.at(pass_info.ps_entry_point);
glAttachShader(pass_data.program, vs_shader_id);
glAttachShader(pass_data.program, fs_shader_id);
glLinkProgram(pass_data.program);
glDetachShader(pass_data.program, vs_shader_id);
glDetachShader(pass_data.program, fs_shader_id);
const auto convert_blend_op = [](reshadefx::pass_blend_op value) -> GLenum {
switch (value)
{
default:
case reshadefx::pass_blend_op::add: return GL_FUNC_ADD;
case reshadefx::pass_blend_op::subtract: return GL_FUNC_SUBTRACT;
case reshadefx::pass_blend_op::rev_subtract: return GL_FUNC_REVERSE_SUBTRACT;
case reshadefx::pass_blend_op::min: return GL_MIN;
case reshadefx::pass_blend_op::max: return GL_MAX;
}
};
const auto convert_blend_func = [](reshadefx::pass_blend_func value) -> GLenum {
switch (value)
{
case reshadefx::pass_blend_func::zero: return GL_ZERO;
default:
case reshadefx::pass_blend_func::one: return GL_ONE;
case reshadefx::pass_blend_func::src_color: return GL_SRC_COLOR;
case reshadefx::pass_blend_func::src_alpha: return GL_SRC_ALPHA;
case reshadefx::pass_blend_func::inv_src_color: return GL_ONE_MINUS_SRC_COLOR;
case reshadefx::pass_blend_func::inv_src_alpha: return GL_ONE_MINUS_SRC_ALPHA;
case reshadefx::pass_blend_func::dst_color: return GL_DST_COLOR;
case reshadefx::pass_blend_func::dst_alpha: return GL_DST_ALPHA;
case reshadefx::pass_blend_func::inv_dst_color: return GL_ONE_MINUS_DST_COLOR;
case reshadefx::pass_blend_func::inv_dst_alpha: return GL_ONE_MINUS_DST_ALPHA;
}
};
const auto convert_stencil_op = [](reshadefx::pass_stencil_op value) -> GLenum {
switch (value)
{
case reshadefx::pass_stencil_op::zero: return GL_ZERO;
default:
case reshadefx::pass_stencil_op::keep: return GL_KEEP;
case reshadefx::pass_stencil_op::invert: return GL_INVERT;
case reshadefx::pass_stencil_op::replace: return GL_REPLACE;
case reshadefx::pass_stencil_op::incr: return GL_INCR_WRAP;
case reshadefx::pass_stencil_op::incr_sat: return GL_INCR;
case reshadefx::pass_stencil_op::decr: return GL_DECR_WRAP;
case reshadefx::pass_stencil_op::decr_sat: return GL_DECR;
}
};
const auto convert_stencil_func = [](reshadefx::pass_stencil_func value) -> GLenum {
switch (value)
{
case reshadefx::pass_stencil_func::never: return GL_NEVER;
case reshadefx::pass_stencil_func::equal: return GL_EQUAL;
case reshadefx::pass_stencil_func::not_equal: return GL_NOTEQUAL;
case reshadefx::pass_stencil_func::less: return GL_LESS;
case reshadefx::pass_stencil_func::less_equal: return GL_LEQUAL;
case reshadefx::pass_stencil_func::greater: return GL_GREATER;
case reshadefx::pass_stencil_func::greater_equal: return GL_GEQUAL;
default:
case reshadefx::pass_stencil_func::always: return GL_ALWAYS;
}
};
pass_data.blend_eq_color = convert_blend_op(pass_info.blend_op);
pass_data.blend_eq_alpha = convert_blend_op(pass_info.blend_op_alpha);
pass_data.blend_src = convert_blend_func(pass_info.src_blend);
pass_data.blend_dest = convert_blend_func(pass_info.dest_blend);
pass_data.blend_src_alpha = convert_blend_func(pass_info.src_blend_alpha);
pass_data.blend_dest_alpha = convert_blend_func(pass_info.dest_blend_alpha);
pass_data.stencil_func = convert_stencil_func(pass_info.stencil_comparison_func);
pass_data.stencil_op_z_pass = convert_stencil_op(pass_info.stencil_op_pass);
pass_data.stencil_op_fail = convert_stencil_op(pass_info.stencil_op_fail);
pass_data.stencil_op_z_fail = convert_stencil_op(pass_info.stencil_op_depth_fail);
glGenFramebuffers(1, &pass_data.fbo);
glBindFramebuffer(GL_FRAMEBUFFER, pass_data.fbo);
if (pass_info.render_target_names[0].empty())
{
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, _rbo[RBO_COLOR]);
pass_data.draw_targets[0] = GL_COLOR_ATTACHMENT0;
pass_data.draw_textures[0] = _tex[TEX_BACK_SRGB];
pass_info.viewport_width = _width;
pass_info.viewport_height = _height;
}
else
{
for (uint32_t k = 0; k < 8 && !pass_info.render_target_names[k].empty(); ++k)
{
opengl_tex_data *const tex_impl = static_cast<opengl_tex_data *>(
look_up_texture_by_name(pass_info.render_target_names[k]).impl);
pass_data.draw_targets[k] = GL_COLOR_ATTACHMENT0 + k;
pass_data.draw_textures[k] = tex_impl->id[pass_info.srgb_write_enable];
glFramebufferTexture(GL_FRAMEBUFFER, pass_data.draw_targets[k], pass_data.draw_textures[k], 0);
}
assert(pass_info.viewport_width != 0 && pass_info.viewport_height != 0);
}
if (pass_info.stencil_enable && // Only need to attach stencil if stencil is actually used in this pass
pass_info.viewport_width == _width &&
pass_info.viewport_height == _height)
{
// Only attach stencil when viewport matches back buffer or else the frame buffer will always be resized to those dimensions
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, _rbo[RBO_STENCIL]);
}
assert(glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE);
}
GLint status = GL_FALSE;
glGetProgramiv(pass_data.program, GL_LINK_STATUS, &status);
if (GL_FALSE == status)
{
GLint log_size = 0;
glGetProgramiv(pass_data.program, GL_INFO_LOG_LENGTH, &log_size);
std::vector<char> log(log_size);
glGetProgramInfoLog(pass_data.program, log_size, nullptr, log.data());
effect.errors += log.data();
LOG(ERROR) << "Failed to link program for pass " << pass_index << " in technique '" << technique.name << "'.";
success = false;
break;
}
}
}
for (auto &it : entry_points)
glDeleteShader(it.second);
return success;
}
void reshade::opengl::runtime_gl::unload_effect(size_t index)
{
for (technique &tech : _techniques)
{
if (tech.effect_index != index)
continue;
const auto impl = static_cast<opengl_technique_data *>(tech.impl);
if (impl == nullptr)
continue;
glDeleteQueries(1, &impl->query);
for (opengl_pass_data &pass_data : impl->passes)
{
if (pass_data.program)
glDeleteProgram(pass_data.program);
glDeleteFramebuffers(1, &pass_data.fbo);
}
delete impl;
tech.impl = nullptr;
}
runtime::unload_effect(index);
if (index < _effect_ubos.size())
{
glDeleteBuffers(1, &_effect_ubos[index]);
_effect_ubos[index] = 0;
}
}
void reshade::opengl::runtime_gl::unload_effects()
{
for (technique &tech : _techniques)
{
const auto impl = static_cast<opengl_technique_data *>(tech.impl);
if (impl == nullptr)
continue;
glDeleteQueries(1, &impl->query);
for (opengl_pass_data &pass_data : impl->passes)
{
if (pass_data.program)
glDeleteProgram(pass_data.program);
glDeleteFramebuffers(1, &pass_data.fbo);
}
delete impl;
tech.impl = nullptr;
}
runtime::unload_effects();
glDeleteBuffers(static_cast<GLsizei>(_effect_ubos.size()), _effect_ubos.data());
_effect_ubos.clear();
for (const auto &info : _effect_sampler_states)
glDeleteSamplers(1, &info.second);
_effect_sampler_states.clear();
}
bool reshade::opengl::runtime_gl::init_texture(texture &texture)
{
auto impl = new opengl_tex_data();
texture.impl = impl;
switch (texture.impl_reference)
{
case texture_reference::back_buffer:
impl->id[0] = _tex[TEX_BACK];
impl->id[1] = _tex[TEX_BACK_SRGB];
return true;
case texture_reference::depth_buffer:
#if RESHADE_DEPTH
impl->id[0] = impl->id[1] =
_copy_depth_source ? _tex[TEX_DEPTH] : _depth_source;
#endif
return true;
}
GLenum internal_format = GL_RGBA8;
GLenum internal_format_srgb = GL_NONE;
switch (texture.format)
{
case reshadefx::texture_format::r8:
internal_format = GL_R8;
break;
case reshadefx::texture_format::r16f:
internal_format = GL_R16F;
break;
case reshadefx::texture_format::r32f:
internal_format = GL_R32F;
break;
case reshadefx::texture_format::rg8:
internal_format = GL_RG8;
break;
case reshadefx::texture_format::rg16:
internal_format = GL_RG16;
break;
case reshadefx::texture_format::rg16f:
internal_format = GL_RG16F;
break;
case reshadefx::texture_format::rg32f:
internal_format = GL_RG32F;
break;
case reshadefx::texture_format::rgba8:
internal_format = GL_RGBA8;
internal_format_srgb = GL_SRGB8_ALPHA8;
break;
case reshadefx::texture_format::rgba16:
internal_format = GL_RGBA16;
break;
case reshadefx::texture_format::rgba16f:
internal_format = GL_RGBA16F;
break;
case reshadefx::texture_format::rgba32f:
internal_format = GL_RGBA32F;
break;
case reshadefx::texture_format::rgb10a2:
internal_format = GL_RGB10_A2;
break;
}
impl->internal_format = internal_format;
// Get current state
GLint previous_tex = 0;
GLint previous_draw_buffer = 0;
GLint previous_frame_buffer = 0;
glGetIntegerv(GL_TEXTURE_BINDING_2D, &previous_tex);
glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, &previous_frame_buffer);
glGetIntegerv(GL_DRAW_BUFFER, &previous_draw_buffer);
// Allocate texture storage
glGenTextures(2, impl->id);
glBindTexture(GL_TEXTURE_2D, impl->id[0]);
glTexStorage2D(GL_TEXTURE_2D, texture.levels, internal_format, texture.width, texture.height);
// Only create SRGB texture view if necessary
if (internal_format_srgb != GL_NONE) {
glTextureView(impl->id[1], GL_TEXTURE_2D, impl->id[0], internal_format_srgb, 0, texture.levels, 0, 1);
}
else {
impl->id[1] = impl->id[0];
}
// Clear texture to zero since by default its contents are undefined
// Use a separate FBO here to make sure there is no mismatch with the dimensions of others
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, _fbo[FBO_CLEAR]);
glFramebufferTexture(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, impl->id[0], 0);
assert(glCheckFramebufferStatus(GL_DRAW_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE);
glDrawBuffer(GL_COLOR_ATTACHMENT0);
const GLuint clear_color[4] = { 0, 0, 0, 0 };
glClearBufferuiv(GL_COLOR, 0, clear_color);
glFramebufferTexture(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, 0, 0);
// Restore previous state from application
glBindTexture(GL_TEXTURE_2D, previous_tex);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, previous_frame_buffer);
glDrawBuffer(previous_draw_buffer);
return true;
}
void reshade::opengl::runtime_gl::upload_texture(const texture &texture, const uint8_t *pixels)
{
auto impl = static_cast<opengl_tex_data *>(texture.impl);
assert(impl != nullptr && pixels != nullptr && texture.impl_reference == texture_reference::none);
unsigned int upload_pitch = texture.width * 4;
std::vector<uint8_t> upload_data(pixels, pixels + upload_pitch * texture.height);
// Flip image data horizontally
std::vector<uint8_t> temp_image_line(upload_pitch);
for (uint32_t y = 0; 2 * y < texture.height; y++)
{
const auto temp = temp_image_line.data();
const auto line1 = upload_data.data() + upload_pitch * (y);
const auto line2 = upload_data.data() + upload_pitch * (texture.height - 1 - y);
std::memcpy(temp, line1, upload_pitch);
std::memcpy(line1, line2, upload_pitch);
std::memcpy(line2, temp, upload_pitch);
}
temp_image_line.clear(); // Free up temporary memory now
// Get current state
GLint previous_tex = 0;
GLint previous_unpack = 0;
GLint previous_unpack_lsb = GL_FALSE;
GLint previous_unpack_swap = GL_FALSE;
GLint previous_unpack_alignment = 0;
GLint previous_unpack_row_length = 0;
GLint previous_unpack_image_height = 0;
GLint previous_unpack_skip_rows = 0;
GLint previous_unpack_skip_pixels = 0;
GLint previous_unpack_skip_images = 0;
glGetIntegerv(GL_TEXTURE_BINDING_2D, &previous_tex);
glGetIntegerv(GL_PIXEL_UNPACK_BUFFER_BINDING, &previous_unpack);
glGetIntegerv(GL_UNPACK_LSB_FIRST, &previous_unpack_lsb);
glGetIntegerv(GL_UNPACK_SWAP_BYTES, &previous_unpack_swap);
glGetIntegerv(GL_UNPACK_ALIGNMENT, &previous_unpack_alignment);
glGetIntegerv(GL_UNPACK_ROW_LENGTH, &previous_unpack_row_length);
glGetIntegerv(GL_UNPACK_IMAGE_HEIGHT, &previous_unpack_image_height);
glGetIntegerv(GL_UNPACK_SKIP_ROWS, &previous_unpack_skip_rows);
glGetIntegerv(GL_UNPACK_SKIP_PIXELS, &previous_unpack_skip_pixels);
glGetIntegerv(GL_UNPACK_SKIP_IMAGES, &previous_unpack_skip_images);
// Unset any existing unpack buffer so pointer is not interpreted as an offset
glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);
// Clear pixel storage modes to defaults (texture uploads can break otherwise)
glPixelStorei(GL_UNPACK_LSB_FIRST, GL_FALSE);
glPixelStorei(GL_UNPACK_SWAP_BYTES, GL_FALSE);
glPixelStorei(GL_UNPACK_ALIGNMENT, 4); // RGBA data is 4-byte aligned
glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
glPixelStorei(GL_UNPACK_IMAGE_HEIGHT, 0);
glPixelStorei(GL_UNPACK_SKIP_ROWS, 0);
glPixelStorei(GL_UNPACK_SKIP_PIXELS, 0);
glPixelStorei(GL_UNPACK_SKIP_IMAGES, 0);
// Bind and upload texture data
glBindTexture(GL_TEXTURE_2D, impl->id[0]);
glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, texture.width, texture.height, GL_RGBA, GL_UNSIGNED_BYTE, upload_data.data());
if (texture.levels > 1)
glGenerateMipmap(GL_TEXTURE_2D);
// Restore previous state from application
glBindTexture(GL_TEXTURE_2D, previous_tex);
glBindBuffer(GL_PIXEL_UNPACK_BUFFER, previous_unpack);
glPixelStorei(GL_UNPACK_LSB_FIRST, previous_unpack_lsb);
glPixelStorei(GL_UNPACK_SWAP_BYTES, previous_unpack_swap);
glPixelStorei(GL_UNPACK_ALIGNMENT, previous_unpack_alignment);
glPixelStorei(GL_UNPACK_ROW_LENGTH, previous_unpack_row_length);
glPixelStorei(GL_UNPACK_IMAGE_HEIGHT, previous_unpack_image_height);
glPixelStorei(GL_UNPACK_SKIP_ROWS, previous_unpack_skip_rows);
glPixelStorei(GL_UNPACK_SKIP_PIXELS, previous_unpack_skip_pixels);
glPixelStorei(GL_UNPACK_SKIP_IMAGES, previous_unpack_skip_images);
}
void reshade::opengl::runtime_gl::destroy_texture(texture &texture)
{
if (texture.impl == nullptr)
return;
auto impl = static_cast<opengl_tex_data *>(texture.impl);
if (texture.impl_reference == texture_reference::none) {
glDeleteTextures(impl->id[0] != impl->id[1] ? 2 : 1, impl->id);
}
delete impl;
texture.impl = nullptr;
}
void reshade::opengl::runtime_gl::render_technique(technique &technique)
{
assert(_app_state.has_state);
const auto impl = static_cast<opengl_technique_data *>(technique.impl);
if (GLuint available = 0; impl->query_in_flight)
{
glGetQueryObjectuiv(impl->query, GL_QUERY_RESULT_AVAILABLE, &available);
if (GLuint64 elapsed_time = 0; available != GL_FALSE)
{
glGetQueryObjectui64v(impl->query, GL_QUERY_RESULT, &elapsed_time);
technique.average_gpu_duration.append(elapsed_time);
impl->query_in_flight = false; // Reset query status
}
}
if (!impl->query_in_flight) {
glBeginQuery(GL_TIME_ELAPSED, impl->query);
}
// Set up global state
glDisable(GL_CULL_FACE);
glDisable(GL_DEPTH_TEST);
glDisable(GL_SCISSOR_TEST);
glFrontFace(GL_CCW);
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
glDepthMask(GL_FALSE); // No need to write to the depth buffer
glBindVertexArray(_vao[VAO_FX]); // This is an empty vertex array object