Debian Codegraph @

Source/Core/VideoBackends/OGL/OGLGfx.cpp

raw symbols SCIP
1 // Copyright 2023 Dolphin Emulator Project
2 // SPDX-License-Identifier: GPL-2.0-or-later
3
4 #include "VideoBackends/OGL/OGLGfx.h"
5
6 #include "Common/GL/GLContext.h"
7 #include "Common/GL/GLExtensions/GLExtensions.h"
8 #include "Common/GL/GLUtil.h"
9 #include "Common/Logging/LogManager.h"
10
11 #include "VideoBackends/OGL/OGLConfig.h"
12 #include "VideoBackends/OGL/OGLPipeline.h"
13 #include "VideoBackends/OGL/OGLShader.h"
14 #include "VideoBackends/OGL/OGLTexture.h"
15 #include "VideoBackends/OGL/ProgramShaderCache.h"
16 #include "VideoBackends/OGL/SamplerCache.h"
17
18 #include "VideoCommon/AsyncShaderCompiler.h"
19 #include "VideoCommon/DriverDetails.h"
20 #include "VideoCommon/Present.h"
21 #include "VideoCommon/VideoConfig.h"
22
23 #include <algorithm>
24 #include <string_view>
25
26 namespace OGL
27 {
28 VideoConfig g_ogl_config;
29
30 static void APIENTRY ErrorCallback(GLenum source, GLenum type, GLuint id, GLenum severity,
31 GLsizei length, const char* message, const void* userParam)
32 {
33 const char* s_source;
34 const char* s_type;
35
36 // Performance - DualCore driver performance warning:
37 // DualCore application thread syncing with server thread
38 if (id == 0x200b0)
39 return;
40
41 switch (source)
42 {
43 case GL_DEBUG_SOURCE_API_ARB:
44 s_source = "API";
45 break;
46 case GL_DEBUG_SOURCE_WINDOW_SYSTEM_ARB:
47 s_source = "Window System";
48 break;
49 case GL_DEBUG_SOURCE_SHADER_COMPILER_ARB:
50 s_source = "Shader Compiler";
51 break;
52 case GL_DEBUG_SOURCE_THIRD_PARTY_ARB:
53 s_source = "Third Party";
54 break;
55 case GL_DEBUG_SOURCE_APPLICATION_ARB:
56 s_source = "Application";
57 break;
58 case GL_DEBUG_SOURCE_OTHER_ARB:
59 s_source = "Other";
60 break;
61 default:
62 s_source = "Unknown";
63 break;
64 }
65 switch (type)
66 {
67 case GL_DEBUG_TYPE_ERROR_ARB:
68 s_type = "Error";
69 break;
70 case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR_ARB:
71 s_type = "Deprecated";
72 break;
73 case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR_ARB:
74 s_type = "Undefined";
75 break;
76 case GL_DEBUG_TYPE_PORTABILITY_ARB:
77 s_type = "Portability";
78 break;
79 case GL_DEBUG_TYPE_PERFORMANCE_ARB:
80 s_type = "Performance";
81 break;
82 case GL_DEBUG_TYPE_OTHER_ARB:
83 s_type = "Other";
84 break;
85 default:
86 s_type = "Unknown";
87 break;
88 }
89 switch (severity)
90 {
91 case GL_DEBUG_SEVERITY_HIGH_ARB:
92 ERROR_LOG_FMT(HOST_GPU, "id: {:x}, source: {}, type: {} - {}", id, s_source, s_type, message);
93 break;
94 case GL_DEBUG_SEVERITY_MEDIUM_ARB:
95 WARN_LOG_FMT(HOST_GPU, "id: {:x}, source: {}, type: {} - {}", id, s_source, s_type, message);
96 break;
97 case GL_DEBUG_SEVERITY_LOW_ARB:
98 DEBUG_LOG_FMT(HOST_GPU, "id: {:x}, source: {}, type: {} - {}", id, s_source, s_type, message);
99 break;
100 case GL_DEBUG_SEVERITY_NOTIFICATION:
101 DEBUG_LOG_FMT(HOST_GPU, "id: {:x}, source: {}, type: {} - {}", id, s_source, s_type, message);
102 break;
103 default:
104 ERROR_LOG_FMT(HOST_GPU, "id: {:x}, source: {}, type: {} - {}", id, s_source, s_type, message);
105 break;
106 }
107 }
108
109 // Two small Fallbacks to avoid GL_ARB_ES2_compatibility
110 static void APIENTRY DepthRangef(GLfloat neardepth, GLfloat fardepth)
111 {
112 glDepthRange(neardepth, fardepth);
113 }
114 static void APIENTRY ClearDepthf(GLfloat depthval)
115 {
116 glClearDepth(depthval);
117 }
118
119 OGLGfx::OGLGfx(std::unique_ptr<GLContext> main_gl_context, float backbuffer_scale)
120 : m_main_gl_context(std::move(main_gl_context)),
121 m_current_rasterization_state(RenderState::GetInvalidRasterizationState()),
122 m_current_depth_state(RenderState::GetInvalidDepthState()),
123 m_current_blend_state(RenderState::GetInvalidBlendingState()),
124 m_backbuffer_scale(backbuffer_scale)
125 {
126 // Create the window framebuffer.
127 if (!m_main_gl_context->IsHeadless())
128 {
129 m_system_framebuffer = std::make_unique<OGLFramebuffer>(
130 nullptr, nullptr, std::vector<AbstractTexture*>{}, AbstractTextureFormat::RGBA8,
131 AbstractTextureFormat::Undefined, std::max(m_main_gl_context->GetBackBufferWidth(), 1u),
132 std::max(m_main_gl_context->GetBackBufferHeight(), 1u), 1, 1, 0);
133 m_current_framebuffer = m_system_framebuffer.get();
134 }
135
136 if (!m_main_gl_context->IsGLES())
137 {
138 // OpenGL 3 doesn't provide GLES like float functions for depth.
139 // They are in core in OpenGL 4.1, so almost every driver should support them.
140 // But for the oldest ones, we provide fallbacks to the old double functions.
141 if (!GLExtensions::Supports("GL_ARB_ES2_compatibility"))
142 {
143 glDepthRangef = DepthRangef;
144 glClearDepthf = ClearDepthf;
145 }
146 }
147
148 InitDriverInfo();
149
150 // Setup Debug logging
151 if (g_ogl_config.bSupportsDebug)
152 {
153 if (GLExtensions::Supports("GL_KHR_debug"))
154 {
155 glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, nullptr, true);
156 glDebugMessageCallback(ErrorCallback, nullptr);
157 }
158 else
159 {
160 glDebugMessageControlARB(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, nullptr, true);
161 glDebugMessageCallbackARB(ErrorCallback, nullptr);
162 }
163 if (Common::Log::LogManager::GetInstance()->IsEnabled(Common::Log::LogType::HOST_GPU,
164 Common::Log::LogLevel::LERROR))
165 {
166 glEnable(GL_DEBUG_OUTPUT);
167 }
168 else
169 {
170 glDisable(GL_DEBUG_OUTPUT);
171 }
172 }
173
174 // Handle VSync on/off
175 if (!DriverDetails::HasBug(DriverDetails::BUG_BROKEN_VSYNC))
176 m_main_gl_context->SwapInterval(g_ActiveConfig.bVSyncActive);
177
178 if (g_backend_info.bSupportsClipControl)
179 glClipControl(GL_LOWER_LEFT, GL_ZERO_TO_ONE);
180
181 if (g_backend_info.bSupportsDepthClamp)
182 {
183 glEnable(GL_CLIP_DISTANCE0);
184 glEnable(GL_CLIP_DISTANCE1);
185 glEnable(GL_DEPTH_CLAMP);
186 }
187
188 glPixelStorei(GL_UNPACK_ALIGNMENT, 4); // 4-byte pixel alignment
189
190 glGenFramebuffers(1, &m_shared_read_framebuffer);
191 glGenFramebuffers(1, &m_shared_draw_framebuffer);
192
193 if (g_backend_info.bSupportsPrimitiveRestart)
194 GLUtil::EnablePrimitiveRestart(m_main_gl_context.get());
195
196 UpdateActiveConfig();
197 }
198
199 OGLGfx::~OGLGfx()
200 {
201 glDeleteFramebuffers(1, &m_shared_draw_framebuffer);
202 glDeleteFramebuffers(1, &m_shared_read_framebuffer);
203 }
204
205 bool OGLGfx::IsHeadless() const
206 {
207 return m_main_gl_context->IsHeadless();
208 }
209
210 std::unique_ptr<AbstractTexture> OGLGfx::CreateTexture(const TextureConfig& config,
211 std::string_view name)
212 {
213 return std::make_unique<OGLTexture>(config, name);
214 }
215
216 std::unique_ptr<AbstractStagingTexture> OGLGfx::CreateStagingTexture(StagingTextureType type,
217 const TextureConfig& config)
218 {
219 return OGLStagingTexture::Create(type, config);
220 }
221
222 std::unique_ptr<AbstractFramebuffer>
223 OGLGfx::CreateFramebuffer(AbstractTexture* color_attachment, AbstractTexture* depth_attachment,
224 std::vector<AbstractTexture*> additional_color_attachments)
225 {
226 return OGLFramebuffer::Create(static_cast<OGLTexture*>(color_attachment),
227 static_cast<OGLTexture*>(depth_attachment),
228 std::move(additional_color_attachments));
229 }
230
231 std::unique_ptr<AbstractShader>
232 OGLGfx::CreateShaderFromSource(ShaderStage stage, std::string_view source,
233 VideoCommon::ShaderIncluder* shader_includer, std::string_view name)
234 {
235 return OGLShader::CreateFromSource(stage, source, shader_includer, name);
236 }
237
238 std::unique_ptr<AbstractShader> OGLGfx::CreateShaderFromBinary(ShaderStage /* stage */,
239 const void* /* data */,
240 size_t /* length */,
241 std::string_view /* name */)
242 {
243 return nullptr;
244 }
245
246 std::unique_ptr<AbstractPipeline> OGLGfx::CreatePipeline(const AbstractPipelineConfig& config,
247 const void* cache_data,
248 size_t cache_data_length)
249 {
250 return OGLPipeline::Create(config, cache_data, cache_data_length);
251 }
252
253 void OGLGfx::SetScissorRect(const MathUtil::Rectangle<int>& rc)
254 {
255 glScissor(rc.left, rc.top, rc.GetWidth(), rc.GetHeight());
256 }
257
258 void OGLGfx::SetViewport(float x, float y, float width, float height, float near_depth,
259 float far_depth)
260 {
261 if (g_ogl_config.bSupportViewportFloat)
262 {
263 glViewportIndexedf(0, x, y, width, height);
264 }
265 else
266 {
267 auto iceilf = [](float f) { return static_cast<GLint>(std::ceil(f)); };
268 glViewport(iceilf(x), iceilf(y), iceilf(width), iceilf(height));
269 }
270
271 glDepthRangef(near_depth, far_depth);
272 }
273
274 void OGLGfx::Draw(u32 base_vertex, u32 num_vertices)
275 {
276 glDrawArrays(static_cast<const OGLPipeline*>(m_current_pipeline)->GetGLPrimitive(), base_vertex,
277 num_vertices);
278 }
279
280 void OGLGfx::DrawIndexed(u32 base_index, u32 num_indices, u32 base_vertex)
281 {
282 if (g_ogl_config.bSupportsGLBaseVertex)
283 {
284 glDrawElementsBaseVertex(static_cast<const OGLPipeline*>(m_current_pipeline)->GetGLPrimitive(),
285 num_indices, GL_UNSIGNED_SHORT,
286 static_cast<u16*>(nullptr) + base_index, base_vertex);
287 }
288 else
289 {
290 glDrawElements(static_cast<const OGLPipeline*>(m_current_pipeline)->GetGLPrimitive(),
291 num_indices, GL_UNSIGNED_SHORT, static_cast<u16*>(nullptr) + base_index);
292 }
293 }
294
295 void OGLGfx::DispatchComputeShader(const AbstractShader* shader, u32 groupsize_x, u32 groupsize_y,
296 u32 groupsize_z, u32 groups_x, u32 groups_y, u32 groups_z)
297 {
298 glUseProgram(static_cast<const OGLShader*>(shader)->GetGLComputeProgramID());
299 glDispatchCompute(groups_x, groups_y, groups_z);
300
301 // We messed up the program binding, so restore it.
302 ProgramShaderCache::InvalidateLastProgram();
303 if (m_current_pipeline)
304 static_cast<const OGLPipeline*>(m_current_pipeline)->GetProgram()->shader.Bind();
305
306 // Barrier to texture can be used for reads.
307 if (std::ranges::any_of(m_bound_image_textures,
308 [](const auto* image) { return image != nullptr; }))
309 {
310 glMemoryBarrier(GL_TEXTURE_UPDATE_BARRIER_BIT);
311 }
312 }
313
314 void OGLGfx::SelectLeftBuffer()
315 {
316 glDrawBuffer(GL_BACK_LEFT);
317 }
318
319 void OGLGfx::SelectRightBuffer()
320 {
321 glDrawBuffer(GL_BACK_RIGHT);
322 }
323
324 void OGLGfx::SelectMainBuffer()
325 {
326 glDrawBuffer(GL_BACK);
327 }
328
329 void OGLGfx::SetFramebuffer(AbstractFramebuffer* framebuffer)
330 {
331 if (m_current_framebuffer == framebuffer)
332 return;
333
334 glBindFramebuffer(GL_FRAMEBUFFER, static_cast<OGLFramebuffer*>(framebuffer)->GetFBO());
335 m_current_framebuffer = framebuffer;
336 }
337
338 void OGLGfx::SetAndDiscardFramebuffer(AbstractFramebuffer* framebuffer)
339 {
340 // EXT_discard_framebuffer could be used here to save bandwidth on tilers.
341 SetFramebuffer(framebuffer);
342 }
343
344 void OGLGfx::SetAndClearFramebuffer(AbstractFramebuffer* framebuffer, const ClearColor& color_value,
345 float depth_value)
346 {
347 SetFramebuffer(framebuffer);
348
349 glDisable(GL_SCISSOR_TEST);
350 GLbitfield clear_mask = 0;
351 if (framebuffer->HasColorBuffer())
352 {
353 glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
354 glClearColor(color_value[0], color_value[1], color_value[2], color_value[3]);
355 clear_mask |= GL_COLOR_BUFFER_BIT;
356 }
357 if (framebuffer->HasDepthBuffer())
358 {
359 glDepthMask(GL_TRUE);
360 glClearDepthf(depth_value);
361 clear_mask |= GL_DEPTH_BUFFER_BIT;
362 }
363 glClear(clear_mask);
364 glEnable(GL_SCISSOR_TEST);
365
366 // Restore color/depth mask.
367 if (framebuffer->HasColorBuffer())
368 {
369 glColorMask(m_current_blend_state.color_update, m_current_blend_state.color_update,
370 m_current_blend_state.color_update, m_current_blend_state.alpha_update);
371 }
372 if (framebuffer->HasDepthBuffer())
373 glDepthMask(m_current_depth_state.update_enable);
374 }
375
376 void OGLGfx::ClearRegion(const MathUtil::Rectangle<int>& target_rc, bool colorEnable,
377 bool alphaEnable, bool zEnable, u32 color, u32 z)
378 {
379 u32 clear_mask = 0;
380 if (colorEnable || alphaEnable)
381 {
382 glColorMask(colorEnable, colorEnable, colorEnable, alphaEnable);
383 glClearColor(float((color >> 16) & 0xFF) / 255.0f, float((color >> 8) & 0xFF) / 255.0f,
384 float((color >> 0) & 0xFF) / 255.0f, float((color >> 24) & 0xFF) / 255.0f);
385 clear_mask = GL_COLOR_BUFFER_BIT;
386 }
387 if (zEnable)
388 {
389 glDepthMask(zEnable ? GL_TRUE : GL_FALSE);
390 glClearDepthf(float(z & 0xFFFFFF) / 16777216.0f);
391 clear_mask |= GL_DEPTH_BUFFER_BIT;
392 }
393
394 // Update rect for clearing the picture
395 // glColorMask/glDepthMask/glScissor affect glClear (glViewport does not)
396 g_gfx->SetScissorRect(target_rc);
397
398 glClear(clear_mask);
399
400 // Restore color/depth mask.
401 if (colorEnable || alphaEnable)
402 {
403 glColorMask(m_current_blend_state.color_update, m_current_blend_state.color_update,
404 m_current_blend_state.color_update, m_current_blend_state.alpha_update);
405 }
406 if (zEnable)
407 glDepthMask(m_current_depth_state.update_enable);
408 }
409
410 bool OGLGfx::BindBackbuffer(const ClearColor& clear_color)
411 {
412 CheckForSurfaceChange();
413 CheckForSurfaceResize();
414 SetAndClearFramebuffer(m_system_framebuffer.get(), clear_color);
415 return true;
416 }
417
418 void OGLGfx::PresentBackbuffer()
419 {
420 if (g_ogl_config.bSupportsDebug)
421 {
422 if (Common::Log::LogManager::GetInstance()->IsEnabled(Common::Log::LogType::HOST_GPU,
423 Common::Log::LogLevel::LERROR))
424 {
425 glEnable(GL_DEBUG_OUTPUT);
426 }
427 else
428 {
429 glDisable(GL_DEBUG_OUTPUT);
430 }
431 }
432
433 // Swap the back and front buffers, presenting the image.
434 m_main_gl_context->Swap();
435 }
436
437 void OGLGfx::OnConfigChanged(u32 bits)
438 {
439 AbstractGfx::OnConfigChanged(bits);
440
441 if (bits & CONFIG_CHANGE_BIT_VSYNC && !DriverDetails::HasBug(DriverDetails::BUG_BROKEN_VSYNC))
442 m_main_gl_context->SwapInterval(g_ActiveConfig.bVSyncActive);
443
444 if (bits & CONFIG_CHANGE_BIT_ANISOTROPY)
445 g_sampler_cache->Clear();
446 }
447
448 void OGLGfx::Flush()
449 {
450 // ensure all commands are sent to the GPU.
451 // Otherwise the driver could batch several frames together.
452 glFlush();
453 }
454
455 void OGLGfx::WaitForGPUIdle()
456 {
457 glFinish();
458 }
459
460 void OGLGfx::CheckForSurfaceChange()
461 {
462 if (!g_presenter->SurfaceChangedTestAndClear())
463 return;
464
465 m_main_gl_context->UpdateSurface(g_presenter->GetNewSurfaceHandle());
466
467 u32 width = m_main_gl_context->GetBackBufferWidth();
468 u32 height = m_main_gl_context->GetBackBufferHeight();
469
470 // With a surface change, the window likely has new dimensions.
471 g_presenter->SetBackbuffer(width, height);
472 m_system_framebuffer->UpdateDimensions(width, height);
473 }
474
475 void OGLGfx::CheckForSurfaceResize()
476 {
477 if (!g_presenter->SurfaceResizedTestAndClear())
478 return;
479
480 m_main_gl_context->Update();
481 u32 width = m_main_gl_context->GetBackBufferWidth();
482 u32 height = m_main_gl_context->GetBackBufferHeight();
483 g_presenter->SetBackbuffer(width, height);
484 m_system_framebuffer->UpdateDimensions(width, height);
485 }
486
487 void OGLGfx::BeginUtilityDrawing()
488 {
489 AbstractGfx::BeginUtilityDrawing();
490 if (g_backend_info.bSupportsDepthClamp)
491 {
492 glDisable(GL_CLIP_DISTANCE0);
493 glDisable(GL_CLIP_DISTANCE1);
494 }
495 }
496
497 void OGLGfx::EndUtilityDrawing()
498 {
499 AbstractGfx::EndUtilityDrawing();
500 if (g_backend_info.bSupportsDepthClamp)
501 {
502 glEnable(GL_CLIP_DISTANCE0);
503 glEnable(GL_CLIP_DISTANCE1);
504 }
505 }
506
507 void OGLGfx::ApplyRasterizationState(const RasterizationState state)
508 {
509 if (m_current_rasterization_state == state)
510 return;
511
512 // none, ccw, cw, ccw
513 if (state.cull_mode != CullMode::None)
514 {
515 // TODO: GX_CULL_ALL not supported, yet!
516 glEnable(GL_CULL_FACE);
517 glFrontFace(state.cull_mode == CullMode::Front ? GL_CCW : GL_CW);
518 }
519 else
520 {
521 glDisable(GL_CULL_FACE);
522 }
523
524 m_current_rasterization_state = state;
525 }
526
527 void OGLGfx::ApplyDepthState(const DepthState state)
528 {
529 if (m_current_depth_state == state)
530 return;
531
532 const GLenum glCmpFuncs[8] = {GL_NEVER, GL_LESS, GL_EQUAL, GL_LEQUAL,
533 GL_GREATER, GL_NOTEQUAL, GL_GEQUAL, GL_ALWAYS};
534
535 if (state.test_enable)
536 {
537 glEnable(GL_DEPTH_TEST);
538 glDepthMask(state.update_enable ? GL_TRUE : GL_FALSE);
539 glDepthFunc(glCmpFuncs[u32(state.func.Value())]);
540 }
541 else
542 {
543 // if the test is disabled write is disabled too
544 // TODO: When PE performance metrics are being emulated via occlusion queries, we should
545 // (probably?) enable depth test with depth function ALWAYS here
546 glDisable(GL_DEPTH_TEST);
547 glDepthMask(GL_FALSE);
548 }
549
550 m_current_depth_state = state;
551 }
552
553 void OGLGfx::ApplyBlendingState(const BlendingState state)
554 {
555 if (m_current_blend_state == state)
556 return;
557
558 bool useDualSource = state.use_dual_src;
559
560 const GLenum src_factors[8] = {GL_ZERO,
561 GL_ONE,
562 GL_DST_COLOR,
563 GL_ONE_MINUS_DST_COLOR,
564 useDualSource ? GL_SRC1_ALPHA : (GLenum)GL_SRC_ALPHA,
565 useDualSource ? GL_ONE_MINUS_SRC1_ALPHA :
566 (GLenum)GL_ONE_MINUS_SRC_ALPHA,
567 GL_DST_ALPHA,
568 GL_ONE_MINUS_DST_ALPHA};
569 const GLenum dst_factors[8] = {GL_ZERO,
570 GL_ONE,
571 GL_SRC_COLOR,
572 GL_ONE_MINUS_SRC_COLOR,
573 useDualSource ? GL_SRC1_ALPHA : (GLenum)GL_SRC_ALPHA,
574 useDualSource ? GL_ONE_MINUS_SRC1_ALPHA :
575 (GLenum)GL_ONE_MINUS_SRC_ALPHA,
576 GL_DST_ALPHA,
577 GL_ONE_MINUS_DST_ALPHA};
578
579 if (state.blend_enable)
580 glEnable(GL_BLEND);
581 else
582 glDisable(GL_BLEND);
583
584 // Always call glBlendEquationSeparate and glBlendFuncSeparate, even when
585 // GL_BLEND is disabled, as a workaround for some bugs (possibly graphics
586 // driver issues?). See https://bugs.dolphin-emu.org/issues/10120 : "Sonic
587 // Adventure 2 Battle: graphics crash when loading first Dark level"
588 GLenum equation = state.subtract ? GL_FUNC_REVERSE_SUBTRACT : GL_FUNC_ADD;
589 GLenum equationAlpha = state.subtract_alpha ? GL_FUNC_REVERSE_SUBTRACT : GL_FUNC_ADD;
590 glBlendEquationSeparate(equation, equationAlpha);
591 glBlendFuncSeparate(src_factors[u32(state.src_factor.Value())],
592 dst_factors[u32(state.dst_factor.Value())],
593 src_factors[u32(state.src_factor_alpha.Value())],
594 dst_factors[u32(state.dst_factor_alpha.Value())]);
595
596 const GLenum logic_op_codes[16] = {
597 GL_CLEAR, GL_AND, GL_AND_REVERSE, GL_COPY, GL_AND_INVERTED, GL_NOOP,
598 GL_XOR, GL_OR, GL_NOR, GL_EQUIV, GL_INVERT, GL_OR_REVERSE,
599 GL_COPY_INVERTED, GL_OR_INVERTED, GL_NAND, GL_SET};
600
601 // Logic ops aren't available in GLES3
602 if (!IsGLES())
603 {
604 if (state.logic_op_enable)
605 {
606 glEnable(GL_COLOR_LOGIC_OP);
607 glLogicOp(logic_op_codes[u32(state.logic_mode.Value())]);
608 }
609 else
610 {
611 glDisable(GL_COLOR_LOGIC_OP);
612 }
613 }
614
615 glColorMask(state.color_update, state.color_update, state.color_update, state.alpha_update);
616 m_current_blend_state = state;
617 }
618
619 void OGLGfx::SetPipeline(const AbstractPipeline* pipeline)
620 {
621 if (m_current_pipeline == pipeline)
622 return;
623
624 if (pipeline)
625 {
626 ApplyRasterizationState(static_cast<const OGLPipeline*>(pipeline)->GetRasterizationState());
627 ApplyDepthState(static_cast<const OGLPipeline*>(pipeline)->GetDepthState());
628 ApplyBlendingState(static_cast<const OGLPipeline*>(pipeline)->GetBlendingState());
629 ProgramShaderCache::BindVertexFormat(
630 static_cast<const OGLPipeline*>(pipeline)->GetVertexFormat());
631 static_cast<const OGLPipeline*>(pipeline)->GetProgram()->shader.Bind();
632 }
633 else
634 {
635 ProgramShaderCache::InvalidateLastProgram();
636 glUseProgram(0);
637 }
638 m_current_pipeline = pipeline;
639 }
640
641 void OGLGfx::SetTexture(u32 index, const AbstractTexture* texture)
642 {
643 const OGLTexture* gl_texture = static_cast<const OGLTexture*>(texture);
644 if (m_bound_textures[index] == gl_texture)
645 return;
646
647 glActiveTexture(GL_TEXTURE0 + index);
648 if (gl_texture)
649 glBindTexture(gl_texture->GetGLTarget(), gl_texture->GetGLTextureId());
650 else
651 glBindTexture(GL_TEXTURE_2D_ARRAY, 0);
652 m_bound_textures[index] = gl_texture;
653 }
654
655 void OGLGfx::SetSamplerState(u32 index, const SamplerState& state)
656 {
657 g_sampler_cache->SetSamplerState(index, state);
658 }
659
660 void OGLGfx::SetComputeImageTexture(u32 index, AbstractTexture* texture, bool read, bool write)
661 {
662 if (m_bound_image_textures[index] == texture)
663 return;
664
665 if (texture)
666 {
667 const GLenum access = read ? (write ? GL_READ_WRITE : GL_READ_ONLY) : GL_WRITE_ONLY;
668 glBindImageTexture(index, static_cast<OGLTexture*>(texture)->GetGLTextureId(), 0, GL_TRUE, 0,
669 access, static_cast<OGLTexture*>(texture)->GetGLFormatForImageTexture());
670 }
671 else
672 {
673 glBindImageTexture(index, 0, 0, GL_FALSE, 0, GL_READ_ONLY, GL_RGBA8);
674 }
675
676 m_bound_image_textures[index] = texture;
677 }
678
679 void OGLGfx::UnbindTexture(const AbstractTexture* texture)
680 {
681 for (size_t i = 0; i < m_bound_textures.size(); i++)
682 {
683 if (m_bound_textures[i] != texture)
684 continue;
685
686 glActiveTexture(static_cast<GLenum>(GL_TEXTURE0 + i));
687 glBindTexture(GL_TEXTURE_2D_ARRAY, 0);
688 m_bound_textures[i] = nullptr;
689 }
690
691 for (size_t i = 0; i < m_bound_image_textures.size(); i++)
692 {
693 if (m_bound_image_textures[i] != texture)
694 continue;
695
696 glBindImageTexture(static_cast<GLuint>(i), 0, 0, GL_FALSE, 0, GL_READ_ONLY, GL_RGBA8);
697 m_bound_image_textures[i] = nullptr;
698 }
699 }
700
701 std::unique_ptr<VideoCommon::AsyncShaderCompiler> OGLGfx::CreateAsyncShaderCompiler()
702 {
703 return std::make_unique<SharedContextAsyncShaderCompiler>();
704 }
705
706 bool OGLGfx::IsGLES() const
707 {
708 return m_main_gl_context->IsGLES();
709 }
710
711 void OGLGfx::BindSharedReadFramebuffer()
712 {
713 glBindFramebuffer(GL_READ_FRAMEBUFFER, m_shared_read_framebuffer);
714 }
715
716 void OGLGfx::BindSharedDrawFramebuffer()
717 {
718 glBindFramebuffer(GL_DRAW_FRAMEBUFFER, m_shared_draw_framebuffer);
719 }
720
721 void OGLGfx::RestoreFramebufferBinding()
722 {
723 glBindFramebuffer(
724 GL_FRAMEBUFFER,
725 m_current_framebuffer ? static_cast<OGLFramebuffer*>(m_current_framebuffer)->GetFBO() : 0);
726 }
727
728 SurfaceInfo OGLGfx::GetSurfaceInfo() const
729 {
730 return {std::max(m_main_gl_context->GetBackBufferWidth(), 1u),
731 std::max(m_main_gl_context->GetBackBufferHeight(), 1u), m_backbuffer_scale,
732 AbstractTextureFormat::RGBA8};
733 }
734
735 } // namespace OGL