-
Notifications
You must be signed in to change notification settings - Fork 326
/
Copy pathRmlUi_Renderer_GL3.cpp
2184 lines (1820 loc) · 71.6 KB
/
RmlUi_Renderer_GL3.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
/*
* This source file is part of RmlUi, the HTML/CSS Interface Middleware
*
* For the latest information, see http://github.com/mikke89/RmlUi
*
* Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd
* Copyright (c) 2019-2023 The RmlUi Team, and contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
#include "RmlUi_Renderer_GL3.h"
#include <RmlUi/Core/Core.h>
#include <RmlUi/Core/DecorationTypes.h>
#include <RmlUi/Core/FileInterface.h>
#include <RmlUi/Core/Geometry.h>
#include <RmlUi/Core/Log.h>
#include <RmlUi/Core/MeshUtilities.h>
#include <RmlUi/Core/Platform.h>
#include <RmlUi/Core/SystemInterface.h>
#include <algorithm>
#include <string.h>
#if defined(RMLUI_PLATFORM_WIN32) && !defined(__MINGW32__)
// function call missing argument list
#pragma warning(disable : 4551)
// unreferenced local function has been removed
#pragma warning(disable : 4505)
#endif
#if defined RMLUI_PLATFORM_EMSCRIPTEN
#define RMLUI_SHADER_HEADER_VERSION "#version 300 es\nprecision highp float;\n"
#include <GLES3/gl3.h>
#elif defined RMLUI_GL3_CUSTOM_LOADER
#define RMLUI_SHADER_HEADER_VERSION "#version 330\n"
#include RMLUI_GL3_CUSTOM_LOADER
#else
#define RMLUI_SHADER_HEADER_VERSION "#version 330\n"
#define GLAD_GL_IMPLEMENTATION
#include "RmlUi_Include_GL3.h"
#endif
// Determines the anti-aliasing quality when creating layers. Enables better-looking visuals, especially when transforms are applied.
#ifndef RMLUI_NUM_MSAA_SAMPLES
#define RMLUI_NUM_MSAA_SAMPLES 2
#endif
#define MAX_NUM_STOPS 16
#define BLUR_SIZE 7
#define BLUR_NUM_WEIGHTS ((BLUR_SIZE + 1) / 2)
#define RMLUI_STRINGIFY_IMPL(x) #x
#define RMLUI_STRINGIFY(x) RMLUI_STRINGIFY_IMPL(x)
#define RMLUI_SHADER_HEADER \
RMLUI_SHADER_HEADER_VERSION "#define MAX_NUM_STOPS " RMLUI_STRINGIFY(MAX_NUM_STOPS) "\n#line " RMLUI_STRINGIFY(__LINE__) "\n"
static const char* shader_vert_main = RMLUI_SHADER_HEADER R"(
uniform vec2 _translate;
uniform mat4 _transform;
in vec2 inPosition;
in vec4 inColor0;
in vec2 inTexCoord0;
out vec2 fragTexCoord;
out vec4 fragColor;
void main() {
fragTexCoord = inTexCoord0;
fragColor = inColor0;
vec2 translatedPos = inPosition + _translate;
vec4 outPos = _transform * vec4(translatedPos, 0.0, 1.0);
gl_Position = outPos;
}
)";
static const char* shader_frag_texture = RMLUI_SHADER_HEADER R"(
uniform sampler2D _tex;
in vec2 fragTexCoord;
in vec4 fragColor;
out vec4 finalColor;
void main() {
vec4 texColor = texture(_tex, fragTexCoord);
finalColor = fragColor * texColor;
}
)";
static const char* shader_frag_color = RMLUI_SHADER_HEADER R"(
in vec2 fragTexCoord;
in vec4 fragColor;
out vec4 finalColor;
void main() {
finalColor = fragColor;
}
)";
enum class ShaderGradientFunction { Linear, Radial, Conic, RepeatingLinear, RepeatingRadial, RepeatingConic }; // Must match shader definitions below.
static const char* shader_frag_gradient = RMLUI_SHADER_HEADER R"(
#define LINEAR 0
#define RADIAL 1
#define CONIC 2
#define REPEATING_LINEAR 3
#define REPEATING_RADIAL 4
#define REPEATING_CONIC 5
#define PI 3.14159265
uniform int _func; // one of the above definitions
uniform vec2 _p; // linear: starting point, radial: center, conic: center
uniform vec2 _v; // linear: vector to ending point, radial: 2d curvature (inverse radius), conic: angled unit vector
uniform vec4 _stop_colors[MAX_NUM_STOPS];
uniform float _stop_positions[MAX_NUM_STOPS]; // normalized, 0 -> starting point, 1 -> ending point
uniform int _num_stops;
in vec2 fragTexCoord;
in vec4 fragColor;
out vec4 finalColor;
vec4 mix_stop_colors(float t) {
vec4 color = _stop_colors[0];
for (int i = 1; i < _num_stops; i++)
color = mix(color, _stop_colors[i], smoothstep(_stop_positions[i-1], _stop_positions[i], t));
return color;
}
void main() {
float t = 0.0;
if (_func == LINEAR || _func == REPEATING_LINEAR)
{
float dist_square = dot(_v, _v);
vec2 V = fragTexCoord - _p;
t = dot(_v, V) / dist_square;
}
else if (_func == RADIAL || _func == REPEATING_RADIAL)
{
vec2 V = fragTexCoord - _p;
t = length(_v * V);
}
else if (_func == CONIC || _func == REPEATING_CONIC)
{
mat2 R = mat2(_v.x, -_v.y, _v.y, _v.x);
vec2 V = R * (fragTexCoord - _p);
t = 0.5 + atan(-V.x, V.y) / (2.0 * PI);
}
if (_func == REPEATING_LINEAR || _func == REPEATING_RADIAL || _func == REPEATING_CONIC)
{
float t0 = _stop_positions[0];
float t1 = _stop_positions[_num_stops - 1];
t = t0 + mod(t - t0, t1 - t0);
}
finalColor = fragColor * mix_stop_colors(t);
}
)";
// "Creation" by Danilo Guanabara, based on: https://www.shadertoy.com/view/XsXXDn
static const char* shader_frag_creation = RMLUI_SHADER_HEADER R"(
uniform float _value;
uniform vec2 _dimensions;
in vec2 fragTexCoord;
in vec4 fragColor;
out vec4 finalColor;
void main() {
float t = _value;
vec3 c;
float l;
for (int i = 0; i < 3; i++) {
vec2 p = fragTexCoord;
vec2 uv = p;
p -= .5;
p.x *= _dimensions.x / _dimensions.y;
float z = t + float(i) * .07;
l = length(p);
uv += p / l * (sin(z) + 1.) * abs(sin(l * 9. - z - z));
c[i] = .01 / length(mod(uv, 1.) - .5);
}
finalColor = vec4(c / l, fragColor.a);
}
)";
static const char* shader_vert_passthrough = RMLUI_SHADER_HEADER R"(
in vec2 inPosition;
in vec2 inTexCoord0;
out vec2 fragTexCoord;
void main() {
fragTexCoord = inTexCoord0;
gl_Position = vec4(inPosition, 0.0, 1.0);
}
)";
static const char* shader_frag_passthrough = RMLUI_SHADER_HEADER R"(
uniform sampler2D _tex;
in vec2 fragTexCoord;
out vec4 finalColor;
void main() {
finalColor = texture(_tex, fragTexCoord);
}
)";
static const char* shader_frag_color_matrix = RMLUI_SHADER_HEADER R"(
uniform sampler2D _tex;
uniform mat4 _color_matrix;
in vec2 fragTexCoord;
out vec4 finalColor;
void main() {
// The general case uses a 4x5 color matrix for full rgba transformation, plus a constant term with the last column.
// However, we only consider the case of rgb transformations. Thus, we could in principle use a 3x4 matrix, but we
// keep the alpha row for simplicity.
// In the general case we should do the matrix transformation in non-premultiplied space. However, without alpha
// transformations, we can do it directly in premultiplied space to avoid the extra division and multiplication
// steps. In this space, the constant term needs to be multiplied by the alpha value, instead of unity.
vec4 texColor = texture(_tex, fragTexCoord);
vec3 transformedColor = vec3(_color_matrix * texColor);
finalColor = vec4(transformedColor, texColor.a);
}
)";
static const char* shader_frag_blend_mask = RMLUI_SHADER_HEADER R"(
uniform sampler2D _tex;
uniform sampler2D _texMask;
in vec2 fragTexCoord;
out vec4 finalColor;
void main() {
vec4 texColor = texture(_tex, fragTexCoord);
float maskAlpha = texture(_texMask, fragTexCoord).a;
finalColor = texColor * maskAlpha;
}
)";
#define RMLUI_SHADER_BLUR_HEADER \
RMLUI_SHADER_HEADER "\n#define BLUR_SIZE " RMLUI_STRINGIFY(BLUR_SIZE) "\n#define BLUR_NUM_WEIGHTS " RMLUI_STRINGIFY(BLUR_NUM_WEIGHTS)
static const char* shader_vert_blur = RMLUI_SHADER_BLUR_HEADER R"(
uniform vec2 _texelOffset;
in vec3 inPosition;
in vec2 inTexCoord0;
out vec2 fragTexCoord[BLUR_SIZE];
void main() {
for(int i = 0; i < BLUR_SIZE; i++)
fragTexCoord[i] = inTexCoord0 - float(i - BLUR_NUM_WEIGHTS + 1) * _texelOffset;
gl_Position = vec4(inPosition, 1.0);
}
)";
static const char* shader_frag_blur = RMLUI_SHADER_BLUR_HEADER R"(
uniform sampler2D _tex;
uniform float _weights[BLUR_NUM_WEIGHTS];
uniform vec2 _texCoordMin;
uniform vec2 _texCoordMax;
in vec2 fragTexCoord[BLUR_SIZE];
out vec4 finalColor;
void main() {
vec4 color = vec4(0.0, 0.0, 0.0, 0.0);
for(int i = 0; i < BLUR_SIZE; i++)
{
vec2 in_region = step(_texCoordMin, fragTexCoord[i]) * step(fragTexCoord[i], _texCoordMax);
color += texture(_tex, fragTexCoord[i]) * in_region.x * in_region.y * _weights[abs(i - BLUR_NUM_WEIGHTS + 1)];
}
finalColor = color;
}
)";
static const char* shader_frag_drop_shadow = RMLUI_SHADER_HEADER R"(
uniform sampler2D _tex;
uniform vec2 _texCoordMin;
uniform vec2 _texCoordMax;
uniform vec4 _color;
in vec2 fragTexCoord;
out vec4 finalColor;
void main() {
vec2 in_region = step(_texCoordMin, fragTexCoord) * step(fragTexCoord, _texCoordMax);
finalColor = texture(_tex, fragTexCoord).a * in_region.x * in_region.y * _color;
}
)";
enum class ProgramId {
None,
Color,
Texture,
Gradient,
Creation,
Passthrough,
ColorMatrix,
BlendMask,
Blur,
DropShadow,
Count,
};
enum class VertShaderId {
Main,
Passthrough,
Blur,
Count,
};
enum class FragShaderId {
Color,
Texture,
Gradient,
Creation,
Passthrough,
ColorMatrix,
BlendMask,
Blur,
DropShadow,
Count,
};
enum class UniformId {
Translate,
Transform,
Tex,
Color,
ColorMatrix,
TexelOffset,
TexCoordMin,
TexCoordMax,
TexMask,
Weights,
Func,
P,
V,
StopColors,
StopPositions,
NumStops,
Value,
Dimensions,
Count,
};
namespace Gfx {
static const char* const program_uniform_names[(size_t)UniformId::Count] = {"_translate", "_transform", "_tex", "_color", "_color_matrix",
"_texelOffset", "_texCoordMin", "_texCoordMax", "_texMask", "_weights[0]", "_func", "_p", "_v", "_stop_colors[0]", "_stop_positions[0]",
"_num_stops", "_value", "_dimensions"};
enum class VertexAttribute { Position, Color0, TexCoord0, Count };
static const char* const vertex_attribute_names[(size_t)VertexAttribute::Count] = {"inPosition", "inColor0", "inTexCoord0"};
struct VertShaderDefinition {
VertShaderId id;
const char* name_str;
const char* code_str;
};
struct FragShaderDefinition {
FragShaderId id;
const char* name_str;
const char* code_str;
};
struct ProgramDefinition {
ProgramId id;
const char* name_str;
VertShaderId vert_shader;
FragShaderId frag_shader;
};
// clang-format off
static const VertShaderDefinition vert_shader_definitions[] = {
{VertShaderId::Main, "main", shader_vert_main},
{VertShaderId::Passthrough, "passthrough", shader_vert_passthrough},
{VertShaderId::Blur, "blur", shader_vert_blur},
};
static const FragShaderDefinition frag_shader_definitions[] = {
{FragShaderId::Color, "color", shader_frag_color},
{FragShaderId::Texture, "texture", shader_frag_texture},
{FragShaderId::Gradient, "gradient", shader_frag_gradient},
{FragShaderId::Creation, "creation", shader_frag_creation},
{FragShaderId::Passthrough, "passthrough", shader_frag_passthrough},
{FragShaderId::ColorMatrix, "color_matrix", shader_frag_color_matrix},
{FragShaderId::BlendMask, "blend_mask", shader_frag_blend_mask},
{FragShaderId::Blur, "blur", shader_frag_blur},
{FragShaderId::DropShadow, "drop_shadow", shader_frag_drop_shadow},
};
static const ProgramDefinition program_definitions[] = {
{ProgramId::Color, "color", VertShaderId::Main, FragShaderId::Color},
{ProgramId::Texture, "texture", VertShaderId::Main, FragShaderId::Texture},
{ProgramId::Gradient, "gradient", VertShaderId::Main, FragShaderId::Gradient},
{ProgramId::Creation, "creation", VertShaderId::Main, FragShaderId::Creation},
{ProgramId::Passthrough, "passthrough", VertShaderId::Passthrough, FragShaderId::Passthrough},
{ProgramId::ColorMatrix, "color_matrix", VertShaderId::Passthrough, FragShaderId::ColorMatrix},
{ProgramId::BlendMask, "blend_mask", VertShaderId::Passthrough, FragShaderId::BlendMask},
{ProgramId::Blur, "blur", VertShaderId::Blur, FragShaderId::Blur},
{ProgramId::DropShadow, "drop_shadow", VertShaderId::Passthrough, FragShaderId::DropShadow},
};
// clang-format on
template <typename T, typename Enum>
class EnumArray {
public:
const T& operator[](Enum id) const
{
RMLUI_ASSERT((size_t)id < (size_t)Enum::Count);
return ids[size_t(id)];
}
T& operator[](Enum id)
{
RMLUI_ASSERT((size_t)id < (size_t)Enum::Count);
return ids[size_t(id)];
}
auto begin() const { return ids.begin(); }
auto end() const { return ids.end(); }
private:
Rml::Array<T, (size_t)Enum::Count> ids = {};
};
using Programs = EnumArray<GLuint, ProgramId>;
using VertShaders = EnumArray<GLuint, VertShaderId>;
using FragShaders = EnumArray<GLuint, FragShaderId>;
class Uniforms {
public:
GLint Get(ProgramId id, UniformId uniform) const
{
auto it = map.find(ToKey(id, uniform));
if (it != map.end())
return it->second;
return -1;
}
void Insert(ProgramId id, UniformId uniform, GLint location) { map[ToKey(id, uniform)] = location; }
private:
using Key = uint64_t;
Key ToKey(ProgramId id, UniformId uniform) const { return (static_cast<Key>(id) << 32) | static_cast<Key>(uniform); }
Rml::UnorderedMap<Key, GLint> map;
};
struct ProgramData {
Programs programs;
VertShaders vert_shaders;
FragShaders frag_shaders;
Uniforms uniforms;
};
struct CompiledGeometryData {
GLuint vao;
GLuint vbo;
GLuint ibo;
GLsizei draw_count;
};
struct FramebufferData {
int width, height;
GLuint framebuffer;
GLuint color_tex_buffer;
GLuint color_render_buffer;
GLuint depth_stencil_buffer;
bool owns_depth_stencil_buffer;
};
enum class FramebufferAttachment { None, DepthStencil };
static void CheckGLError(const char* operation_name)
{
#ifdef RMLUI_DEBUG
GLenum error_code = glGetError();
if (error_code != GL_NO_ERROR)
{
static const Rml::Pair<GLenum, const char*> error_names[] = {{GL_INVALID_ENUM, "GL_INVALID_ENUM"}, {GL_INVALID_VALUE, "GL_INVALID_VALUE"},
{GL_INVALID_OPERATION, "GL_INVALID_OPERATION"}, {GL_OUT_OF_MEMORY, "GL_OUT_OF_MEMORY"}};
const char* error_str = "''";
for (auto& err : error_names)
{
if (err.first == error_code)
{
error_str = err.second;
break;
}
}
Rml::Log::Message(Rml::Log::LT_ERROR, "OpenGL error during %s. Error code 0x%x (%s).", operation_name, error_code, error_str);
}
#endif
(void)operation_name;
}
// Create the shader, 'shader_type' is either GL_VERTEX_SHADER or GL_FRAGMENT_SHADER.
static bool CreateShader(GLuint& out_shader_id, GLenum shader_type, const char* code_string)
{
RMLUI_ASSERT(shader_type == GL_VERTEX_SHADER || shader_type == GL_FRAGMENT_SHADER);
GLuint id = glCreateShader(shader_type);
glShaderSource(id, 1, (const GLchar**)&code_string, NULL);
glCompileShader(id);
GLint status = 0;
glGetShaderiv(id, GL_COMPILE_STATUS, &status);
if (status == GL_FALSE)
{
GLint info_log_length = 0;
glGetShaderiv(id, GL_INFO_LOG_LENGTH, &info_log_length);
char* info_log_string = new char[info_log_length + 1];
glGetShaderInfoLog(id, info_log_length, NULL, info_log_string);
Rml::Log::Message(Rml::Log::LT_ERROR, "Compile failure in OpenGL shader: %s", info_log_string);
delete[] info_log_string;
glDeleteShader(id);
return false;
}
CheckGLError("CreateShader");
out_shader_id = id;
return true;
}
static bool CreateProgram(GLuint& out_program, Uniforms& inout_uniform_map, ProgramId program_id, GLuint vertex_shader, GLuint fragment_shader)
{
GLuint id = glCreateProgram();
RMLUI_ASSERT(id);
for (GLuint i = 0; i < (GLuint)VertexAttribute::Count; i++)
glBindAttribLocation(id, i, vertex_attribute_names[i]);
CheckGLError("BindAttribLocations");
glAttachShader(id, vertex_shader);
glAttachShader(id, fragment_shader);
glLinkProgram(id);
glDetachShader(id, vertex_shader);
glDetachShader(id, fragment_shader);
GLint status = 0;
glGetProgramiv(id, GL_LINK_STATUS, &status);
if (status == GL_FALSE)
{
GLint info_log_length = 0;
glGetProgramiv(id, GL_INFO_LOG_LENGTH, &info_log_length);
char* info_log_string = new char[info_log_length + 1];
glGetProgramInfoLog(id, info_log_length, NULL, info_log_string);
Rml::Log::Message(Rml::Log::LT_ERROR, "OpenGL program linking failure: %s", info_log_string);
delete[] info_log_string;
glDeleteProgram(id);
return false;
}
out_program = id;
// Make a lookup table for the uniform locations.
GLint num_active_uniforms = 0;
glGetProgramiv(id, GL_ACTIVE_UNIFORMS, &num_active_uniforms);
constexpr size_t name_size = 64;
GLchar name_buf[name_size] = "";
for (int unif = 0; unif < num_active_uniforms; ++unif)
{
GLint array_size = 0;
GLenum type = 0;
GLsizei actual_length = 0;
glGetActiveUniform(id, unif, name_size, &actual_length, &array_size, &type, name_buf);
GLint location = glGetUniformLocation(id, name_buf);
// See if we have the name in our pre-defined name list.
UniformId program_uniform = UniformId::Count;
for (int i = 0; i < (int)UniformId::Count; i++)
{
const char* uniform_name = program_uniform_names[i];
if (strcmp(name_buf, uniform_name) == 0)
{
program_uniform = (UniformId)i;
break;
}
}
if ((size_t)program_uniform < (size_t)UniformId::Count)
{
inout_uniform_map.Insert(program_id, program_uniform, location);
}
else
{
Rml::Log::Message(Rml::Log::LT_ERROR, "OpenGL program uses unknown uniform '%s'.", name_buf);
return false;
}
}
CheckGLError("CreateProgram");
return true;
}
static bool CreateFramebuffer(FramebufferData& out_fb, int width, int height, int samples, FramebufferAttachment attachment,
GLuint shared_depth_stencil_buffer)
{
#ifdef RMLUI_PLATFORM_EMSCRIPTEN
constexpr GLint wrap_mode = GL_CLAMP_TO_EDGE;
#else
constexpr GLint wrap_mode = GL_CLAMP_TO_BORDER; // GL_REPEAT GL_MIRRORED_REPEAT GL_CLAMP_TO_EDGE
#endif
constexpr GLenum color_format = GL_RGBA8; // GL_RGBA8 GL_SRGB8_ALPHA8 GL_RGBA16F
constexpr GLint min_mag_filter = GL_LINEAR; // GL_NEAREST
const Rml::Colourf border_color(0.f, 0.f);
GLuint framebuffer = 0;
glGenFramebuffers(1, &framebuffer);
glBindFramebuffer(GL_FRAMEBUFFER, framebuffer);
GLuint color_tex_buffer = 0;
GLuint color_render_buffer = 0;
if (samples > 0)
{
glGenRenderbuffers(1, &color_render_buffer);
glBindRenderbuffer(GL_RENDERBUFFER, color_render_buffer);
glRenderbufferStorageMultisample(GL_RENDERBUFFER, samples, color_format, width, height);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, color_render_buffer);
}
else
{
glGenTextures(1, &color_tex_buffer);
glBindTexture(GL_TEXTURE_2D, color_tex_buffer);
glTexImage2D(GL_TEXTURE_2D, 0, color_format, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, min_mag_filter);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, min_mag_filter);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrap_mode);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrap_mode);
#ifndef RMLUI_PLATFORM_EMSCRIPTEN
glTexParameterfv(GL_TEXTURE_2D, GL_TEXTURE_BORDER_COLOR, &border_color[0]);
#endif
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, color_tex_buffer, 0);
}
// Create depth/stencil buffer storage attachment.
GLuint depth_stencil_buffer = 0;
if (attachment != FramebufferAttachment::None)
{
if (shared_depth_stencil_buffer)
{
// Share depth/stencil buffer
depth_stencil_buffer = shared_depth_stencil_buffer;
}
else
{
// Create new depth/stencil buffer
glGenRenderbuffers(1, &depth_stencil_buffer);
glBindRenderbuffer(GL_RENDERBUFFER, depth_stencil_buffer);
glRenderbufferStorageMultisample(GL_RENDERBUFFER, samples, GL_DEPTH24_STENCIL8, width, height);
}
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, depth_stencil_buffer);
}
const GLuint framebuffer_status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
if (framebuffer_status != GL_FRAMEBUFFER_COMPLETE)
{
Rml::Log::Message(Rml::Log::LT_ERROR, "OpenGL framebuffer could not be generated. Error code %x.", framebuffer_status);
return false;
}
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glBindTexture(GL_TEXTURE_2D, 0);
glBindRenderbuffer(GL_RENDERBUFFER, 0);
CheckGLError("CreateFramebuffer");
out_fb = {};
out_fb.width = width;
out_fb.height = height;
out_fb.framebuffer = framebuffer;
out_fb.color_tex_buffer = color_tex_buffer;
out_fb.color_render_buffer = color_render_buffer;
out_fb.depth_stencil_buffer = depth_stencil_buffer;
out_fb.owns_depth_stencil_buffer = !shared_depth_stencil_buffer;
return true;
}
static void DestroyFramebuffer(FramebufferData& fb)
{
if (fb.framebuffer)
glDeleteFramebuffers(1, &fb.framebuffer);
if (fb.color_tex_buffer)
glDeleteTextures(1, &fb.color_tex_buffer);
if (fb.color_render_buffer)
glDeleteRenderbuffers(1, &fb.color_render_buffer);
if (fb.owns_depth_stencil_buffer && fb.depth_stencil_buffer)
glDeleteRenderbuffers(1, &fb.depth_stencil_buffer);
fb = {};
}
static void BindTexture(const FramebufferData& fb)
{
if (!fb.color_tex_buffer)
{
RMLUI_ERRORMSG("Only framebuffers with color textures can be bound as textures. This framebuffer probably uses multisampling which needs a "
"blit step first.");
}
glBindTexture(GL_TEXTURE_2D, fb.color_tex_buffer);
}
static bool CreateShaders(ProgramData& data)
{
RMLUI_ASSERT(std::all_of(data.vert_shaders.begin(), data.vert_shaders.end(), [](auto&& value) { return value == 0; }));
RMLUI_ASSERT(std::all_of(data.frag_shaders.begin(), data.frag_shaders.end(), [](auto&& value) { return value == 0; }));
RMLUI_ASSERT(std::all_of(data.programs.begin(), data.programs.end(), [](auto&& value) { return value == 0; }));
auto ReportError = [](const char* type, const char* name) {
Rml::Log::Message(Rml::Log::LT_ERROR, "Could not create OpenGL %s: '%s'.", type, name);
return false;
};
for (const VertShaderDefinition& def : vert_shader_definitions)
{
if (!CreateShader(data.vert_shaders[def.id], GL_VERTEX_SHADER, def.code_str))
return ReportError("vertex shader", def.name_str);
}
for (const FragShaderDefinition& def : frag_shader_definitions)
{
if (!CreateShader(data.frag_shaders[def.id], GL_FRAGMENT_SHADER, def.code_str))
return ReportError("fragment shader", def.name_str);
}
for (const ProgramDefinition& def : program_definitions)
{
if (!CreateProgram(data.programs[def.id], data.uniforms, def.id, data.vert_shaders[def.vert_shader], data.frag_shaders[def.frag_shader]))
return ReportError("program", def.name_str);
}
glUseProgram(data.programs[ProgramId::BlendMask]);
glUniform1i(data.uniforms.Get(ProgramId::BlendMask, UniformId::TexMask), 1);
glUseProgram(0);
return true;
}
static void DestroyShaders(const ProgramData& data)
{
for (GLuint id : data.programs)
glDeleteProgram(id);
for (GLuint id : data.vert_shaders)
glDeleteShader(id);
for (GLuint id : data.frag_shaders)
glDeleteShader(id);
}
} // namespace Gfx
RenderInterface_GL3::RenderInterface_GL3()
{
auto mut_program_data = Rml::MakeUnique<Gfx::ProgramData>();
if (Gfx::CreateShaders(*mut_program_data))
{
program_data = std::move(mut_program_data);
Rml::Mesh mesh;
Rml::MeshUtilities::GenerateQuad(mesh, Rml::Vector2f(-1), Rml::Vector2f(2), {});
fullscreen_quad_geometry = RenderInterface_GL3::CompileGeometry(mesh.vertices, mesh.indices);
}
}
RenderInterface_GL3::~RenderInterface_GL3()
{
if (fullscreen_quad_geometry)
{
RenderInterface_GL3::ReleaseGeometry(fullscreen_quad_geometry);
fullscreen_quad_geometry = {};
}
if (program_data)
{
Gfx::DestroyShaders(*program_data);
program_data.reset();
}
}
void RenderInterface_GL3::SetViewport(int width, int height, int offset_x, int offset_y)
{
viewport_width = Rml::Math::Max(width, 1);
viewport_height = Rml::Math::Max(height, 1);
viewport_offset_x = offset_x;
viewport_offset_y = offset_y;
projection = Rml::Matrix4f::ProjectOrtho(0, (float)viewport_width, (float)viewport_height, 0, -10000, 10000);
}
void RenderInterface_GL3::BeginFrame()
{
RMLUI_ASSERT(viewport_width >= 1 && viewport_height >= 1);
// Backup GL state.
glstate_backup.enable_cull_face = glIsEnabled(GL_CULL_FACE);
glstate_backup.enable_blend = glIsEnabled(GL_BLEND);
glstate_backup.enable_stencil_test = glIsEnabled(GL_STENCIL_TEST);
glstate_backup.enable_scissor_test = glIsEnabled(GL_SCISSOR_TEST);
glstate_backup.enable_depth_test = glIsEnabled(GL_DEPTH_TEST);
glGetIntegerv(GL_VIEWPORT, glstate_backup.viewport);
glGetIntegerv(GL_SCISSOR_BOX, glstate_backup.scissor);
glGetIntegerv(GL_ACTIVE_TEXTURE, &glstate_backup.active_texture);
glGetIntegerv(GL_STENCIL_CLEAR_VALUE, &glstate_backup.stencil_clear_value);
glGetFloatv(GL_COLOR_CLEAR_VALUE, glstate_backup.color_clear_value);
glGetBooleanv(GL_COLOR_WRITEMASK, glstate_backup.color_writemask);
glGetIntegerv(GL_BLEND_EQUATION_RGB, &glstate_backup.blend_equation_rgb);
glGetIntegerv(GL_BLEND_EQUATION_ALPHA, &glstate_backup.blend_equation_alpha);
glGetIntegerv(GL_BLEND_SRC_RGB, &glstate_backup.blend_src_rgb);
glGetIntegerv(GL_BLEND_DST_RGB, &glstate_backup.blend_dst_rgb);
glGetIntegerv(GL_BLEND_SRC_ALPHA, &glstate_backup.blend_src_alpha);
glGetIntegerv(GL_BLEND_DST_ALPHA, &glstate_backup.blend_dst_alpha);
glGetIntegerv(GL_STENCIL_FUNC, &glstate_backup.stencil_front.func);
glGetIntegerv(GL_STENCIL_REF, &glstate_backup.stencil_front.ref);
glGetIntegerv(GL_STENCIL_VALUE_MASK, &glstate_backup.stencil_front.value_mask);
glGetIntegerv(GL_STENCIL_WRITEMASK, &glstate_backup.stencil_front.writemask);
glGetIntegerv(GL_STENCIL_FAIL, &glstate_backup.stencil_front.fail);
glGetIntegerv(GL_STENCIL_PASS_DEPTH_FAIL, &glstate_backup.stencil_front.pass_depth_fail);
glGetIntegerv(GL_STENCIL_PASS_DEPTH_PASS, &glstate_backup.stencil_front.pass_depth_pass);
glGetIntegerv(GL_STENCIL_BACK_FUNC, &glstate_backup.stencil_back.func);
glGetIntegerv(GL_STENCIL_BACK_REF, &glstate_backup.stencil_back.ref);
glGetIntegerv(GL_STENCIL_BACK_VALUE_MASK, &glstate_backup.stencil_back.value_mask);
glGetIntegerv(GL_STENCIL_BACK_WRITEMASK, &glstate_backup.stencil_back.writemask);
glGetIntegerv(GL_STENCIL_BACK_FAIL, &glstate_backup.stencil_back.fail);
glGetIntegerv(GL_STENCIL_BACK_PASS_DEPTH_FAIL, &glstate_backup.stencil_back.pass_depth_fail);
glGetIntegerv(GL_STENCIL_BACK_PASS_DEPTH_PASS, &glstate_backup.stencil_back.pass_depth_pass);
// Setup expected GL state.
glViewport(0, 0, viewport_width, viewport_height);
glClearStencil(0);
glClearColor(0, 0, 0, 0);
glActiveTexture(GL_TEXTURE0);
glDisable(GL_SCISSOR_TEST);
glDisable(GL_CULL_FACE);
// Set blending function for premultiplied alpha.
glEnable(GL_BLEND);
glBlendEquation(GL_FUNC_ADD);
glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
#ifndef RMLUI_PLATFORM_EMSCRIPTEN
// We do blending in nonlinear sRGB space because that is the common practice and gives results that we are used to.
glDisable(GL_FRAMEBUFFER_SRGB);
#endif
glEnable(GL_STENCIL_TEST);
glStencilFunc(GL_ALWAYS, 1, GLuint(-1));
glStencilMask(GLuint(-1));
glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
glDisable(GL_DEPTH_TEST);
SetTransform(nullptr);
render_layers.BeginFrame(viewport_width, viewport_height);
glBindFramebuffer(GL_FRAMEBUFFER, render_layers.GetTopLayer().framebuffer);
glClear(GL_COLOR_BUFFER_BIT);
UseProgram(ProgramId::None);
program_transform_dirty.set();
scissor_state = Rml::Rectanglei::MakeInvalid();
Gfx::CheckGLError("BeginFrame");
}
void RenderInterface_GL3::EndFrame()
{
const Gfx::FramebufferData& fb_active = render_layers.GetTopLayer();
const Gfx::FramebufferData& fb_postprocess = render_layers.GetPostprocessPrimary();
// Resolve MSAA to postprocess framebuffer.
glBindFramebuffer(GL_READ_FRAMEBUFFER, fb_active.framebuffer);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fb_postprocess.framebuffer);
glBlitFramebuffer(0, 0, fb_active.width, fb_active.height, 0, 0, fb_postprocess.width, fb_postprocess.height, GL_COLOR_BUFFER_BIT, GL_NEAREST);
// Draw to backbuffer
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glViewport(viewport_offset_x, viewport_offset_y, viewport_width, viewport_height);
// Assuming we have an opaque background, we can just write to it with the premultiplied alpha blend mode and we'll get the correct result.
// Instead, if we had a transparent destination that didn't use premultiplied alpha, we would need to perform a manual un-premultiplication step.
glActiveTexture(GL_TEXTURE0);
Gfx::BindTexture(fb_postprocess);
UseProgram(ProgramId::Passthrough);
DrawFullscreenQuad();
render_layers.EndFrame();
// Restore GL state.
if (glstate_backup.enable_cull_face)
glEnable(GL_CULL_FACE);
else
glDisable(GL_CULL_FACE);
if (glstate_backup.enable_blend)
glEnable(GL_BLEND);
else
glDisable(GL_BLEND);
if (glstate_backup.enable_stencil_test)
glEnable(GL_STENCIL_TEST);
else
glDisable(GL_STENCIL_TEST);
if (glstate_backup.enable_scissor_test)
glEnable(GL_SCISSOR_TEST);
else
glDisable(GL_SCISSOR_TEST);
if (glstate_backup.enable_depth_test)
glEnable(GL_DEPTH_TEST);
else
glDisable(GL_DEPTH_TEST);
glViewport(glstate_backup.viewport[0], glstate_backup.viewport[1], glstate_backup.viewport[2], glstate_backup.viewport[3]);
glScissor(glstate_backup.scissor[0], glstate_backup.scissor[1], glstate_backup.scissor[2], glstate_backup.scissor[3]);
glActiveTexture(glstate_backup.active_texture);
glClearStencil(glstate_backup.stencil_clear_value);
glClearColor(glstate_backup.color_clear_value[0], glstate_backup.color_clear_value[1], glstate_backup.color_clear_value[2],
glstate_backup.color_clear_value[3]);
glColorMask(glstate_backup.color_writemask[0], glstate_backup.color_writemask[1], glstate_backup.color_writemask[2],
glstate_backup.color_writemask[3]);
glBlendEquationSeparate(glstate_backup.blend_equation_rgb, glstate_backup.blend_equation_alpha);
glBlendFuncSeparate(glstate_backup.blend_src_rgb, glstate_backup.blend_dst_rgb, glstate_backup.blend_src_alpha, glstate_backup.blend_dst_alpha);
glStencilFuncSeparate(GL_FRONT, glstate_backup.stencil_front.func, glstate_backup.stencil_front.ref, glstate_backup.stencil_front.value_mask);
glStencilMaskSeparate(GL_FRONT, glstate_backup.stencil_front.writemask);
glStencilOpSeparate(GL_FRONT, glstate_backup.stencil_front.fail, glstate_backup.stencil_front.pass_depth_fail,
glstate_backup.stencil_front.pass_depth_pass);
glStencilFuncSeparate(GL_BACK, glstate_backup.stencil_back.func, glstate_backup.stencil_back.ref, glstate_backup.stencil_back.value_mask);
glStencilMaskSeparate(GL_BACK, glstate_backup.stencil_back.writemask);
glStencilOpSeparate(GL_BACK, glstate_backup.stencil_back.fail, glstate_backup.stencil_back.pass_depth_fail,
glstate_backup.stencil_back.pass_depth_pass);
Gfx::CheckGLError("EndFrame");
}
void RenderInterface_GL3::Clear()
{
glClearColor(0, 0, 0, 1);
glClear(GL_COLOR_BUFFER_BIT);
}
Rml::CompiledGeometryHandle RenderInterface_GL3::CompileGeometry(Rml::Span<const Rml::Vertex> vertices, Rml::Span<const int> indices)
{
constexpr GLenum draw_usage = GL_STATIC_DRAW;
GLuint vao = 0;
GLuint vbo = 0;
GLuint ibo = 0;
glGenVertexArrays(1, &vao);
glGenBuffers(1, &vbo);
glGenBuffers(1, &ibo);
glBindVertexArray(vao);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(Rml::Vertex) * vertices.size(), (const void*)vertices.data(), draw_usage);
glEnableVertexAttribArray((GLuint)Gfx::VertexAttribute::Position);