Blender V5.3
gpu_context.cc
Go to the documentation of this file.
1/* SPDX-FileCopyrightText: 2016 by Mike Erwin. All rights reserved.
2 *
3 * SPDX-License-Identifier: GPL-2.0-or-later */
4
15
16#include "BKE_global.hh"
17
18#include "BLI_assert.hh"
19#include "BLI_threads.hh"
20#include "BLI_vector_set.hh"
21
22#include "DNA_userdef_types.h"
23
24#include "GHOST_IContext.hh"
25#include "GHOST_ISystem.hh"
26#include "GHOST_Types.hh"
27
28#include "GPU_context.hh"
29
30#include "GPU_batch.hh"
31#include "GPU_pass.hh"
32#include "gpu_backend.hh"
34#include "gpu_matrix_private.hh"
35#include "gpu_private.hh"
36#include "gpu_shader_private.hh"
37
38#ifdef WITH_VULKAN_BACKEND
39# include "vk_backend.hh"
40#endif
41#ifdef WITH_OPENGL_BACKEND
42# include "gl_backend.hh"
43# include "gl_context.hh"
44#endif
45#ifdef WITH_METAL_BACKEND
46# include "mtl_backend.hh"
47#endif
48#include "dummy_backend.hh"
49
50#include "draw_debug.hh"
51
52#include <cstdio>
53#include <mutex>
54
55namespace blender {
56
57using namespace blender::gpu;
58
59static thread_local Context *active_ctx = nullptr;
60
62static int num_backend_users = 0;
63
64static void gpu_backend_create();
65static void gpu_backend_discard();
66
67/* -------------------------------------------------------------------- */
70
71namespace gpu {
72
82
84{
85 /* Derived class should have called free_resources already. */
86 BLI_assert(front_left == nullptr);
87 BLI_assert(back_left == nullptr);
88 BLI_assert(front_right == nullptr);
89 BLI_assert(back_right == nullptr);
90 BLI_assert(texture_pool == nullptr);
91
97 delete state_manager;
98 delete imm;
99}
100
121
123{
124 return (this == active_ctx) && pthread_equal(pthread_self(), thread_);
125}
126
128{
129 return active_ctx;
130}
131
133{
134 if (this->dummy_vbo) {
135 return this->dummy_vbo;
136 }
137
138 /* TODO(fclem): get rid of this dummy VBO. */
139 GPUVertFormat format = {0};
140 GPU_vertformat_attr_add(&format, "dummy", gpu::VertAttrType::SFLOAT_32);
141 this->dummy_vbo = GPU_vertbuf_create_with_format(format);
143 return this->dummy_vbo;
144}
145
155
165
175
186
187} // namespace gpu
188
190
191/* -------------------------------------------------------------------- */
192
193GPUContext *GPU_context_create(GHOST_IWindow *ghost_window, GHOST_IContext *ghost_context)
194{
195 {
196 std::scoped_lock lock(backend_users_mutex);
197 if (num_backend_users == 0) {
198 /* Automatically create backend when first context is created. */
200 }
202 }
203
204 BLI_assert(ghost_context);
205 if (ghost_window) {
206 BLI_assert(ghost_context == ghost_window->getDrawingContext());
207 }
208 Context *ctx = GPUBackend::get()->context_alloc(ghost_window, ghost_context);
209
211
213
214 return wrap(ctx);
215}
216
217void GPU_context_discard(GPUContext *ctx_)
218{
219 Context *ctx = unwrap(ctx_);
220 BLI_assert(active_ctx == ctx);
221
223
224 GPUBackend *backend = GPUBackend::get();
225 /* Flush any remaining printf while making sure we are inside render boundaries. */
226 backend->render_begin();
227 printf_end(ctx);
228 backend->render_end();
229
230 delete ctx;
231 active_ctx = nullptr;
232
233 {
234 std::scoped_lock lock(backend_users_mutex);
237 if (num_backend_users == 0) {
238 /* Discard backend when last context is discarded. */
240 }
241 }
242}
243
244void GPU_context_active_set(GPUContext *ctx_)
245{
246 Context *ctx = unwrap(ctx_);
247
248 if (active_ctx) {
251 }
252
253 active_ctx = ctx;
254
255 if (ctx) {
256 ctx->activate();
257 /* It can happen that the previous context drew with a different color-space.
258 * In the case where the new context is drawing with the same shader that was previously bound
259 * (shader binding optimization), the uniform would not be set again because the dirty flag
260 * would not have been set (since the color space of this new context never changed). The
261 * shader would reuse the same color-space as the previous context frame-buffer (see #137855).
262 */
264 }
265}
266
268{
269 return wrap(Context::get());
270}
271
272void GPU_context_begin_frame(GPUContext *ctx)
273{
274 gpu::Context *_ctx = unwrap(ctx);
275 if (_ctx) {
276 _ctx->begin_frame();
277 }
278}
279
280void GPU_context_end_frame(GPUContext *ctx)
281{
282 gpu::Context *_ctx = unwrap(ctx);
283 if (_ctx) {
284 _ctx->end_frame();
285 }
286}
287
288void GPU_context_debug_pipeline_creation(GPUContext *ctx, bool enable)
289{
290 gpu::Context *_ctx = unwrap(ctx);
291 if (_ctx) {
292 _ctx->debug_pipeline_creation = enable;
293 }
294}
295
296/* -------------------------------------------------------------------- */
301
303
305{
306 main_context_mutex.lock();
307}
308
310{
311 main_context_mutex.unlock();
312}
313
315
316/* -------------------------------------------------------------------- */
322
324{
325 GPUBackend *backend = GPUBackend::get();
326 BLI_assert(backend);
327 /* WORKAROUND: Currently a band-aid for the heist production. Has no side effect for GL backend
328 * but should be fixed for Metal. */
329 if (backend) {
330 backend->render_begin();
332 }
333}
335{
336 GPUBackend *backend = GPUBackend::get();
337 BLI_assert(backend);
338 if (backend) {
340 backend->render_end();
341 }
342}
343void GPU_render_step(bool force_resource_release)
344{
345 GPUBackend *backend = GPUBackend::get();
346 BLI_assert(backend);
347 if (backend) {
349 backend->render_step(force_resource_release);
351 }
352
354}
355
357
358/* -------------------------------------------------------------------- */
361
363static std::optional<GPUBackendType> g_backend_type_override = std::nullopt;
364static std::optional<bool> g_backend_type_supported = std::nullopt;
365static std::optional<GHOST_GPUDevice> g_preferred_device_override = std::nullopt;
366static std::optional<int> g_vsync_override = std::nullopt;
367static GPUBackend *g_backend = nullptr;
369
371{
372 g_ghost_system = ghost_system_handle;
373}
374
379
381{
382 g_backend_type = backend;
383 g_backend_type_supported = std::nullopt;
384}
385
387{
388 return g_vsync_override.value();
389}
390
392{
393 g_vsync_override = vsync;
394}
395
397{
398 return g_vsync_override.has_value();
399}
400
405
407{
408 g_backend_type_override = backend_type;
409}
410
415
417 const uint32_t vendor_id,
418 const uint32_t device_id)
419{
420 BLI_assert(index >= 0);
421
422 GHOST_GPUDevice device = {};
423 device.is_override = true;
424 device.fail_on_invalid_override = false;
425 device.index = index;
426 device.vendor_id = vendor_id;
427 device.device_id = device_id;
429}
430
432{
433 if (g_preferred_device_override.has_value()) {
436 device.fallback_index = U.gpu_preferred_index;
437 device.fallback_vendor_id = U.gpu_preferred_vendor_id;
438 device.fallback_device_id = U.gpu_preferred_device_id;
439 return device;
440 }
441
442 GHOST_GPUDevice device = {};
443 device.is_override = false;
444 device.fail_on_invalid_override = false;
445 device.index = U.gpu_preferred_index;
446 device.vendor_id = U.gpu_preferred_vendor_id;
447 device.device_id = U.gpu_preferred_device_id;
448 device.fallback_index = device.index;
449 device.fallback_vendor_id = device.vendor_id;
450 device.fallback_device_id = device.device_id;
451 return device;
452}
453
454static const char *gpu_backend_type_name(const GPUBackendType backend_type)
455{
456 switch (backend_type) {
458 return "OpenGL";
460 return "Vulkan";
462 return "Metal";
463 case GPU_BACKEND_NONE:
464 return "None";
465 case GPU_BACKEND_ANY:
466 break;
467 }
468
469 return "Unknown";
470}
471
472#ifdef WITH_VULKAN_BACKEND
473void GPU_vulkan_supported_devices_print(FILE *fp)
474{
476}
477#endif
478
480{
481 /* Only detect once, can't switch backend until Blender restart. */
482 static bool backend_type_detected = false;
483 if (backend_type_detected) {
485 }
486 backend_type_detected = true;
487
488 VectorSet<GPUBackendType> backends_to_check;
489 if (g_backend_type_override.has_value()) {
490 backends_to_check.add(*g_backend_type_override);
491 }
492#if defined(WITH_OPENGL_BACKEND)
493 backends_to_check.add(GPU_BACKEND_OPENGL);
494#elif defined(WITH_METAL_BACKEND)
495 backends_to_check.add(GPU_BACKEND_METAL);
496#endif
497
498#if defined(WITH_VULKAN_BACKEND)
499 backends_to_check.add(GPU_BACKEND_VULKAN);
500#endif
501
502 for (const GPUBackendType backend_type : backends_to_check) {
503 GPU_backend_type_selection_set(backend_type);
504 if (GPU_backend_supported()) {
505 if (g_preferred_device_override.has_value() && backend_type != GPU_BACKEND_VULKAN) {
506 fprintf(stderr,
507 "Warning: '--gpu-device' is only supported for the Vulkan backend. "
508 "Ignoring the device override for the selected %s backend and falling back to the "
509 "stored GPU preference.\n",
510 gpu_backend_type_name(backend_type));
512 }
513 return true;
514 }
516 }
517
519 return false;
520}
521
523{
524 /* Skip the support check if "--debug-gpu-backend-no-fallback" is used. */
526 return true;
527 }
528
529 switch (g_backend_type) {
531#ifdef WITH_OPENGL_BACKEND
532 return true;
533#else
534 return false;
535#endif
537#ifdef WITH_VULKAN_BACKEND
539#else
540 return false;
541#endif
543#ifdef WITH_METAL_BACKEND
545#else
546 return false;
547#endif
548 case GPU_BACKEND_NONE:
549 return true;
550 default:
551 BLI_assert(false && "No backend specified");
552 return false;
553 }
554}
555
563
565{
566 BLI_assert(g_backend == nullptr);
568
569 switch (g_backend_type) {
570#ifdef WITH_OPENGL_BACKEND
572 g_backend = MEM_new<GLBackend>(__func__);
573 break;
574#endif
575#ifdef WITH_VULKAN_BACKEND
577 g_backend = MEM_new<VKBackend>(__func__);
578 break;
579#endif
580#ifdef WITH_METAL_BACKEND
582 g_backend = MEM_new<MTLBackend>(__func__);
583 break;
584#endif
585 case GPU_BACKEND_NONE:
586 g_backend = MEM_new<DummyBackend>(__func__);
587 break;
588 default:
589 BLI_assert(0);
590 break;
591 }
592}
593
599
605
607{
608 /* TODO: assert no resource left. */
609 MEM_delete(g_backend);
610 g_backend = nullptr;
611}
612
614{
615
616#ifdef WITH_OPENGL_BACKEND
617 if (g_backend && dynamic_cast<GLBackend *>(g_backend) != nullptr) {
618 return GPU_BACKEND_OPENGL;
619 }
620#endif
621
622#ifdef WITH_METAL_BACKEND
623 if (g_backend && dynamic_cast<MTLBackend *>(g_backend) != nullptr) {
624 return GPU_BACKEND_METAL;
625 }
626#endif
627
628#ifdef WITH_VULKAN_BACKEND
629 if (g_backend && dynamic_cast<VKBackend *>(g_backend) != nullptr) {
630 return GPU_BACKEND_VULKAN;
631 }
632#endif
633
634 return GPU_BACKEND_NONE;
635}
636
641
643{
644 return g_backend;
645}
646
648
649/* -------------------------------------------------------------------- */
652
653namespace gpu {
654
656{
658#ifdef WITH_OPENGL_BACKEND
660 return GHOST_kDrawingContextTypeOpenGL;
661#endif
662#ifdef WITH_VULKAN_BACKEND
664 return GHOST_kDrawingContextTypeVulkan;
665#endif
666#ifdef WITH_METAL_BACKEND
668 return GHOST_kDrawingContextTypeMetal;
669#endif
670 default:
673 }
674}
675
677{
678 /* Contexts can only be created on the main thread. */
680
681 GHOST_IContext *main_thread_ghost_context = GHOST_IContext::getActiveDrawingContext();
682 GPUContext *main_thread_gpu_context = GPU_context_active_get();
683
684 /* GPU settings for context creation. */
685 GHOST_GPUSettings gpu_settings = {0};
686 gpu_settings.context_type = ghost_context_type();
687 if (G.debug & G_DEBUG_GPU) {
688 gpu_settings.flags |= GHOST_gpuDebugContext;
689 }
690 if (G.debug & G_DEBUG_GPU_NO_HW_RAYTRACING) {
691 gpu_settings.flags |= GHOST_gpuNoHWRaytracing;
692 }
694
695 /* Grab the system handle. */
697 BLI_assert(ghost_system);
698
699 /* Create a Ghost GPU Context using the system handle. */
700 GHOST_IContext *ghost_context = ghost_system->createOffscreenContext(gpu_settings);
701 BLI_assert(ghost_context);
702
703 /* Activate it so GPU_context_create has a valid device for info queries. */
704 ghost_context->activateDrawingContext();
705
706 /* Create a GPU context for the secondary thread to use. */
707 GPUContext *gpu_context = GPU_context_create(nullptr, ghost_context);
708 BLI_assert(gpu_context);
709
710 /* Release the Ghost GPU Context from this thread. */
711 const GHOST_TSuccess success = ghost_context->releaseDrawingContext();
712 BLI_assert(success);
713 UNUSED_VARS_NDEBUG(success);
714
715 /* Restore the main thread contexts.
716 * (required as the above context creation also makes it active).
717 * Contexts can be unset when called from the event system (#157456) */
718 if (main_thread_ghost_context) {
719 main_thread_ghost_context->activateDrawingContext();
720 }
721 if (main_thread_gpu_context) {
722 GPU_context_active_set(main_thread_gpu_context);
723 }
724
725 return GPUSecondaryContextData{.ghost_context = ghost_context, .gpu_context = gpu_context};
726}
727
729{
730 data.ghost_context->activateDrawingContext();
731 GPU_context_active_set(data.gpu_context);
732}
733
735{
736 GPU_context_active_set(nullptr);
737 data.ghost_context->releaseDrawingContext();
738}
739
741{
743 GPUContext *cur_gpu_context = GPU_context_active_get();
744
746
747 GPU_context_discard(data.gpu_context);
748
749 data.ghost_context->releaseDrawingContext();
750
752 ghost_system->disposeContext(data.ghost_context);
753
754 /* Restore previous GHOST/GPU contexts, unless they are the same
755 * as what is being destroyed. */
756 if (cur_ghost_context && cur_ghost_context != data.ghost_context) {
757 cur_ghost_context->activateDrawingContext();
758 }
759 if (cur_gpu_context != data.gpu_context) {
760 GPU_context_active_set(cur_gpu_context);
761 }
762
763 data.ghost_context = nullptr;
764 data.gpu_context = nullptr;
765}
766
771
773{
774 /* Contexts should be destructed on the thread they were activated. */
776
777 GPU_context_discard(data_.gpu_context);
778
779 data_.ghost_context->releaseDrawingContext();
780
782 BLI_assert(ghost_system);
783 ghost_system->disposeContext(data_.ghost_context);
784}
785
787{
788 /* Contexts need to be activated in the thread they're going to be used. */
790
791 data_.ghost_context->activateDrawingContext();
792 GPU_context_active_set(data_.gpu_context);
793}
794
796
797} // namespace gpu
798} // namespace blender
GHOST_TDrawingContextType
@ GHOST_kDrawingContextTypeNone
GHOST_TSuccess
@ GHOST_gpuNoHWRaytracing
@ GHOST_gpuDebugContext
#define GPU_batch_create(primitive_type, vertex_buf, index_buf)
Definition GPU_batch.hh:143
#define GPU_BATCH_DISCARD_SAFE(batch)
Definition GPU_batch.hh:199
#define GPU_VERTBUF_DISCARD_SAFE(verts)
volatile int lock
#define BLI_assert_unreachable()
#define UNUSED_VARS_NDEBUG(...)
virtual GHOST_TSuccess releaseDrawingContext()=0
static GHOST_IContext * getActiveDrawingContext()
virtual GHOST_TSuccess activateDrawingContext()=0
virtual GHOST_IContext * createOffscreenContext(GHOST_GPUSettings gpu_settings)=0
virtual GHOST_TSuccess disposeContext(GHOST_IContext *context)=0
virtual GHOST_IContext * getDrawingContext()=0
bool add(const Key &key)
static DebugDraw & get()
static Context * get()
GPUMatrixState * matrix_state
Batch * procedural_triangles_batch_get()
VertBuf * dummy_vbo_get()
Batch * procedural_triangle_strips_batch_get()
virtual void activate()=0
static std::atomic< int > context_counter
virtual void end_frame()=0
Batch * procedural_lines_batch_get()
virtual void begin_frame()=0
Batch * procedural_points_batch_get()
virtual void deactivate()=0
virtual void init_resources()=0
virtual void render_end()=0
virtual void render_step(bool force_resource_release=false)=0
virtual void delete_resources()=0
virtual void render_begin()=0
virtual TexturePool * texturepool_alloc()=0
virtual Context * context_alloc(GHOST_IWindow *ghost_window, GHOST_IContext *ghost_context)=0
static GPUBackend * get()
static bool metal_is_supported()
static bool is_supported()
static void supported_devices_print(FILE *fp)
Simple API to draw debug shapes and log in the viewport.
void GPU_activate_secondary_context(const GPUSecondaryContextData &data)
GPUSecondaryContextData GPU_create_secondary_context()
static GHOST_TDrawingContextType ghost_context_type()
BLI_INLINE MTLTexture * unwrap(Texture *tex)
void printf_begin(Context *ctx)
void GPU_deactivate_secondary_context(const GPUSecondaryContextData &data)
BLI_INLINE Texture * wrap(MTLTexture *texture)
void GPU_destroy_secondary_context(GPUSecondaryContextData &data)
void printf_end(Context *ctx)
BMesh Iterators.
UserDef U
Definition blender.cc:58
BLI_assert(slot->slot_subtype.map==BMO_OP_SLOT_SUBTYPE_MAP_FLT)
void GPU_matrix_state_discard(GPUMatrixState *state)
Definition gpu_matrix.cc:76
static void gpu_backend_discard()
static GPUBackendType g_backend_type
GPUContext * GPU_context_create(GHOST_IWindow *ghost_window, GHOST_IContext *ghost_context)
void GPU_context_main_unlock()
GPUBackendType GPU_backend_get_type()
void GPU_context_end_frame(GPUContext *ctx)
void GPU_render_step(bool force_resource_release=false)
bool GPU_backend_supported()
GHOST_ISystem * GPU_backend_ghost_system_get()
bool GPU_backend_type_selection_detect()
static int num_backend_users
@ GPU_PRIM_TRI_STRIP
static void gpu_backend_create()
int GPU_backend_vsync_get()
void GPU_render_begin()
static std::optional< int > g_vsync_override
void GPU_context_active_set(GPUContext *)
bool GPU_backend_type_selection_is_overridden()
static std::optional< bool > g_backend_type_supported
void GPU_context_begin_frame(GPUContext *ctx)
static Mutex backend_users_mutex
@ G_DEBUG_GPU_BACKEND_NO_FALLBACK
@ G_DEBUG_GPU_NO_HW_RAYTRACING
@ G_DEBUG_GPU_DEVICE_NO_FALLBACK
Global G
Definition blender.cc:57
static Mutex main_context_mutex
unsigned int uint32_t
Definition BKE_text.h:81
void GPU_pass_cache_update()
Definition gpu_pass.cc:315
void gpu_backend_delete_resources()
static std::optional< GHOST_GPUDevice > g_preferred_device_override
static std::optional< GPUBackendType > g_backend_type_override
void GPU_render_end()
GPUBackendType GPU_backend_type_selection_get()
BMesh const char void * data
void GPU_backend_vsync_set_override(int vsync)
void GPU_shader_unbind()
void GPU_backend_type_selection_set_override(GPUBackendType backend_type)
static bool gpu_backend_supported()
int BLI_thread_is_main()
Definition threads.cc:184
const char * GPU_backend_get_name()
uint GPU_vertformat_attr_add(GPUVertFormat *format, StringRef name, gpu::VertAttrType type)
GPUMatrixState * GPU_matrix_state_create()
Definition gpu_matrix.cc:57
static GHOST_ISystem * g_ghost_system
void gpu_backend_init_resources()
static Context * active_ctx
@ G_FLAG_GPU_BACKEND_FALLBACK
std::mutex Mutex
Definition BLI_mutex.hh:51
void GPU_vertbuf_data_alloc(gpu::VertBuf &verts, uint v_len)
bool GPU_backend_vsync_is_overridden()
void GPU_backend_ghost_system_set(GHOST_ISystem *ghost_system_handle)
void GPU_context_debug_pipeline_creation(GPUContext *ctx, bool enable)
Enable shader create info pipeline state assert.
GHOST_GPUDevice GPU_backend_preferred_device_get()
void GPU_backend_preferred_device_set_override(int index, uint32_t vendor_id, uint32_t device_id)
static GPUBackend * g_backend
static const char * gpu_backend_type_name(const GPUBackendType backend_type)
void GPU_backend_type_selection_set(const GPUBackendType backend)
void GPU_context_main_lock()
GPUContext * GPU_context_active_get()
void GPU_context_discard(GPUContext *)
bool fail_on_invalid_override
GHOST_TDrawingContextType context_type
GHOST_GPUDevice preferred_device