chore: checkpoint web Blender migration source, tools and docs
Some checks failed
M6 deployable RC / quick (push) Has been cancelled
M6 deployable RC / chromium (push) Has been cancelled
M6 deployable RC / release (push) Has been cancelled

Accumulated uncommitted work: GHOST Web backend, WebGL/GPU web layer,
web workflow engine and protocol, tooling, docs and task records.
Large generated evidence, user-testing archives, build snapshots and
imported test assets remain untracked.

Co-Authored-By: Claude Code <noreply@anthropic.com>
This commit is contained in:
mes123456
2026-11-10 11:18:01 +08:00
parent 122142c26c
commit f3e21c6b98
6887 changed files with 257154 additions and 12294 deletions

View File

@@ -2,19 +2,6 @@
#
# SPDX-License-Identifier: GPL-2.0-or-later
# WebEngine is a data/modeling module. Rendering is implemented by the local
# Three.js adapter, so expose Blender GPU headers but do not compile a second
# renderer into WebAssembly.
if(WITH_WEB)
add_library(bf_gpu INTERFACE)
target_include_directories(bf_gpu INTERFACE
${CMAKE_CURRENT_SOURCE_DIR}
${CMAKE_CURRENT_SOURCE_DIR}/intern
)
add_library(bf::gpu ALIAS bf_gpu)
return()
endif()
set(INC
PUBLIC .
dummy
@@ -22,6 +9,7 @@ set(INC
metal
opengl
vulkan
webgl
../makesrna
# For theme color access.
@@ -456,8 +444,21 @@ set(LIB
PRIVATE bf::dependencies::opencolorio
)
# Select Backend source based on availability
if(WITH_OPENGL_BACKEND)
# Select Backend source based on availability. Web also needs the native shader
# registry and generated sources below, independently of backend selection.
if(EMSCRIPTEN)
list(APPEND SRC
webgl/webgl_backend.cc
webgl/webgl_backend.hh
webgl/webgl_draw.cc
webgl/webgl_draw.hh
webgl/webgl_shader.cc
webgl/webgl_shader.hh
webgl/webgl_texture.cc
webgl/webgl_texture.hh
)
add_definitions(-DWITH_WEBGL_BACKEND)
elseif(WITH_OPENGL_BACKEND)
list(APPEND SRC
${OPENGL_SRC}
)
@@ -914,6 +915,9 @@ endif()
blender_add_lib(bf_gpu "${SRC}" "${INC}" "${INC_SYS}" "${LIB}")
add_library(bf::gpu ALIAS bf_gpu)
if(EMSCRIPTEN)
target_compile_definitions(bf_gpu INTERFACE WITH_WEBGL_BACKEND)
endif()
target_link_libraries(bf_gpu PUBLIC
bf_compositor_shaders
bf_draw_shaders

View File

@@ -108,6 +108,13 @@ void GPU_context_discard(GPUContext *);
void GPU_context_active_set(GPUContext *);
GPUContext *GPU_context_active_get();
/**
* Identity of the active context's allocation lifetime, or uint64_t(-1) if none is active.
* Unlike its address, this identity is not reused when a context is destroyed and recreated.
* Activating an existing context does not change it.
*/
uint64_t GPU_context_active_id_get();
/**
* Begin and end frame are used to mark the singular boundary representing the lifetime of a whole
* frame. This also acts as a divisor for ensuring workload submission and flushing, especially for

View File

@@ -11,6 +11,8 @@
namespace blender {
void GPU_init();
/** Initialize compiler/registry resources for shader-only callers. Does not imply GPU_is_init(). */
void GPU_init_shader_resources();
void GPU_exit();
bool GPU_is_init();

View File

@@ -76,9 +76,18 @@ void GPU_select_finalize();
*/
unsigned int GPU_select_end();
/** Detached sample queries. Keep the result buffer alive until disposal.
* Submit restores drawing state; polling never restores a previous frame's state. */
struct GPUSelectQueryAsync;
GPUSelectQueryAsync *GPU_select_query_submit();
bool GPU_select_query_poll(GPUSelectQueryAsync *query, uint &r_hits);
void GPU_select_query_dispose(GPUSelectQueryAsync *&query);
/* Cache selection region. */
bool GPU_select_is_cached();
/** Revalidate a cached pick against its native GPU context before WM dispatch. */
bool GPU_select_cache_revalidate();
void GPU_select_cache_begin();
void GPU_select_cache_load_id();
void GPU_select_cache_end();

View File

@@ -14,6 +14,13 @@
#include <mutex>
#include <optional>
#ifdef __EMSCRIPTEN__
# include <emscripten/html5.h>
# include <map>
# include <memory>
# include <stdexcept>
#endif
#include "BLI_span.hh"
#include "BLI_string_ref.hh"
#include "BLI_utility_mixins.hh"
@@ -440,6 +447,30 @@ class StaticShader : NonCopyable {
/* Handle for async compilation. */
AsyncCompilationHandle compilation_handle_ = 0;
#ifdef __EMSCRIPTEN__
/* Overlay/GP modules can outlive a canvas and are shared by draw instances.
* Keep the module and its references stable, but never share its WebGL
* programs across browser contexts. Retain earlier variants until module
* release, since another window's recorded passes can still reference them. */
bool context_local_ = false;
std::map<EMSCRIPTEN_WEBGL_CONTEXT_HANDLE, std::unique_ptr<StaticShader>> context_shaders_;
StaticShader &context_shader()
{
const auto context = emscripten_webgl_get_current_context();
if (context <= 0 || emscripten_is_webgl_context_lost(context)) {
throw std::runtime_error("Static shader requires a live browser GPU context");
}
std::scoped_lock lock(mutex_);
auto &shader = context_shaders_[context];
if (!shader) {
shader = std::make_unique<StaticShader>(info_name_);
shader->context_local_ = true;
}
return *shader;
}
#endif
void move(StaticShader &&other)
{
std::scoped_lock lock1(mutex_);
@@ -450,6 +481,10 @@ class StaticShader : NonCopyable {
shader_.exchange(other.shader_.exchange(shader_));
failed_.exchange(other.failed_.exchange(failed_));
std::swap(compilation_handle_, other.compilation_handle_);
#ifdef __EMSCRIPTEN__
std::swap(context_local_, other.context_local_);
context_shaders_.swap(other.context_shaders_);
#endif
}
public:
@@ -477,6 +512,12 @@ class StaticShader : NonCopyable {
/* Schedule the shader to be compile in a worker thread. */
void ensure_compile_async()
{
#ifdef __EMSCRIPTEN__
/* Browser programs belong to the calling canvas. Do not finalize a
* compilation performed with a different worker's WebGL context. */
this->get();
return;
#endif
if (is_ready()) {
return;
}
@@ -500,11 +541,21 @@ class StaticShader : NonCopyable {
bool is_ready()
{
#ifdef __EMSCRIPTEN__
if (!context_local_) {
return context_shader().is_ready();
}
#endif
return shader_ || failed_;
}
gpu::Shader *get()
{
#ifdef __EMSCRIPTEN__
if (!context_local_) {
return context_shader().get();
}
#endif
if (is_ready()) {
return shader_;
}
@@ -519,6 +570,13 @@ class StaticShader : NonCopyable {
BLI_assert(!info_name_.empty());
shader_ = GPU_shader_create_from_info_name(info_name_.c_str());
}
#ifdef __EMSCRIPTEN__
if (!shader_ && emscripten_is_webgl_context_lost(emscripten_webgl_get_current_context())) {
/* Loss during creation is retryable on restoration of this same
* canvas. Do not permanently poison the context's lazy shader slot. */
throw std::runtime_error("Browser GPU context lost during static shader creation");
}
#endif
failed_ = shader_ == nullptr;
}
@@ -529,6 +587,12 @@ class StaticShader : NonCopyable {
/* TODO: Find a better way to handle this. */
void set(gpu::Shader *shader)
{
#ifdef __EMSCRIPTEN__
if (!context_local_) {
context_shader().set(shader);
return;
}
#endif
std::scoped_lock lock(mutex_);
BLI_assert(shader_ == nullptr);
shader_ = shader;

View File

@@ -125,6 +125,9 @@ enum [[host_shared]] GPUSeqFlags : uint32_t {
GPU_SEQ_FLAG_ANY_HANDLE = GPU_SEQ_FLAG_SELECTED_LH | GPU_SEQ_FLAG_SELECTED_RH
};
/* Shared by BLF batching and backends that lower the read-only glyph buffer. */
#define GPU_GLYPH_BATCH_LEN_MAX 128
/* Glyph for text rendering. */
struct [[host_shared]] GlyphQuad {
int4 position;

View File

@@ -220,6 +220,7 @@ GPUStencilTest GPU_stencil_test_get();
*/
float GPU_line_width_get();
bool GPU_line_smooth_get();
bool GPU_polygon_smooth_get();
void GPU_flush();
void GPU_finish();

View File

@@ -0,0 +1,49 @@
/* SPDX-FileCopyrightText: 2026 Blender Authors
*
* SPDX-License-Identifier: GPL-2.0-or-later */
#pragma once
#include <memory>
namespace blender::gpu {
/** Preserve the WebGL shader and native resource slots across buffer producers.
* Unlike StateSnapshot this does not capture or resume a framebuffer/subpass.
* Contents and compute publications remain current. Restore explicitly before
* consuming results; on failure callers must also restore while unwinding.
* Other backends retain their existing resource binding behavior. */
class ResourceBindingSnapshot {
struct Data;
std::unique_ptr<Data> data_;
public:
ResourceBindingSnapshot();
~ResourceBindingSnapshot();
ResourceBindingSnapshot(const ResourceBindingSnapshot &) = delete;
ResourceBindingSnapshot &operator=(const ResourceBindingSnapshot &) = delete;
void restore() const;
};
/** Preserve native pipeline state across an auxiliary draw such as editor picking.
* The caller owns matrices, viewport and framebuffer/attachment lifetimes.
* Framebuffer resume is separate from pipeline restore; on WebGL it also resumes
* native subpasses, shader uniforms and live resource bindings. Released shader
* or buffer/texture owners are never resurrected; restoration reports failure.
* Resource contents and completed compute writes are not rolled back.
* Restore is explicit so a backend failure can propagate on the successful path
* without throwing from an exception-unwinding destructor. */
class StateSnapshot {
struct Data;
std::unique_ptr<Data> data_;
public:
StateSnapshot();
~StateSnapshot();
StateSnapshot(const StateSnapshot &) = delete;
StateSnapshot &operator=(const StateSnapshot &) = delete;
void restore() const;
void restore_framebuffer() const;
};
} // namespace blender::gpu

View File

@@ -18,6 +18,10 @@
#include "GPU_vertex_buffer.hh"
#ifdef __EMSCRIPTEN__
# include <stdexcept>
#endif
namespace blender::gpu {
class Context;
@@ -38,7 +42,7 @@ class VertBuf;
class GPUBackend {
protected:
ShaderCompiler *compiler_;
ShaderCompiler *compiler_ = nullptr;
public:
virtual ~GPUBackend() = default;
@@ -52,6 +56,11 @@ class GPUBackend {
ShaderCompiler *get_compiler()
{
#ifdef __EMSCRIPTEN__
if (!compiler_) {
throw std::runtime_error("Blender GPU shader compiler is not initialized");
}
#endif
return compiler_;
}

View File

@@ -356,7 +356,7 @@ static void polyline_draw_workaround(
Batch *batch, int vertex_first, int vertex_count, int instance_first, int instance_count)
{
/* Early out as this can cause crashes on some backend (see #136831). */
if (vertex_count == 0) {
if (vertex_count < 2) {
return;
}
/* Check compatible input primitive. */
@@ -364,26 +364,36 @@ static void polyline_draw_workaround(
GPU_batch_bind_as_resources(batch, batch->shader);
IndexRange range = GPU_batch_draw_expanded_parameter_get(
batch->prim_type, GPU_PRIM_TRIS, vertex_count, vertex_first, 2);
batch->prim_type, GPU_PRIM_TRIS, vertex_count, 0, 2);
Batch *tri_batch = Context::get()->procedural_triangles_batch_get();
GPU_batch_set_shader(tri_batch, batch->shader);
int vert_stride_count[3] = {(batch->prim_type == GPU_PRIM_LINES) ? 2 : 1, vertex_count, 0};
GPU_shader_uniform_3iv(batch->shader, "gpu_vert_stride_count_offset", vert_stride_count);
/* Expansion and loop wrapping are relative to this draw, then address the parent index buffer. */
const int index_start = vertex_first + (batch->elem ? batch->elem->index_start_get() : 0);
GPU_shader_uniform_1i(batch->shader, "gpu_polyline_index_start", index_start);
/* Assume GPU_FETCH_FLOAT for now. A bit cumbersome to assert for this or to find the correct
* attribute. */
GPU_shader_uniform_1b(batch->shader, "gpu_attr_0_fetch_int", false);
/* Allow byte color fetch. */
const GPUVertFormat *format = GPU_vertbuf_get_format(batch->verts[0]);
int id = GPU_vertformat_attr_id_get(format, "color");
if (id != -1) {
for (int v = 0; v < GPU_BATCH_VBO_MAX_LEN; v++) {
if (!batch->verts[v]) {
continue;
}
const GPUVertFormat *format = GPU_vertbuf_get_format(batch->verts[v]);
int id = GPU_vertformat_attr_id_get(format, "color");
if (id == -1) {
continue;
}
const GPUVertAttr &attr = format->attrs[id];
const bool is_unorm8 = attr.type.format == gpu::VertAttrType::UNORM_8_8_8_8;
BLI_assert_msg(is_unorm8 || attr.type.fetch_mode() == GPU_FETCH_FLOAT,
"color attribute for polylines can only use GPU_FETCH_INT_TO_FLOAT_UNIT or "
"GPU_FETCH_FLOAT");
GPU_shader_uniform_1b(batch->shader, "gpu_attr_1_fetch_unorm8", is_unorm8);
break;
}
GPU_batch_draw_advanced(tri_batch, range.start(), range.size(), instance_first, instance_count);

View File

@@ -13,6 +13,8 @@
* - free can be called from any thread
*/
#include <mutex>
#include "BKE_global.hh"
#include "BLI_assert.h"
@@ -38,7 +40,10 @@
#ifdef WITH_VULKAN_BACKEND
# include "vk_backend.hh"
#endif
#ifdef WITH_OPENGL_BACKEND
#ifdef WITH_WEBGL_BACKEND
# include "GPU_init_exit.hh"
# include "webgl_backend.hh"
#elif defined(WITH_OPENGL_BACKEND)
# include "gl_backend.hh"
# include "gl_context.hh"
#endif
@@ -51,6 +56,9 @@
#include <cstdio>
#include <mutex>
#ifdef WITH_WEBGL_BACKEND
# include <stdexcept>
#endif
namespace blender {
@@ -198,14 +206,40 @@ GPUContext *GPU_context_create(GHOST_IWindow *ghost_window, GHOST_IContext *ghos
/* Automatically create backend when first context is created. */
gpu_backend_create();
}
#ifdef WITH_WEBGL_BACKEND
else if (GPU_backend_get_type() != GPU_backend_type_selection_get()) {
throw std::runtime_error("Cannot change Blender GPU backend while contexts are alive");
}
#endif
num_backend_users++;
}
#ifdef WITH_WEBGL_BACKEND
Context *previous = active_ctx;
Context *ctx = nullptr;
try {
ctx = GPUBackend::get()->context_alloc(ghost_window, ghost_context);
GPU_context_active_set(wrap(ctx));
}
catch (...) {
delete ctx;
active_ctx = nullptr;
GPU_context_active_set(wrap(previous));
std::scoped_lock lock(backend_users_mutex);
if (--num_backend_users == 0) {
gpu_backend_discard();
}
throw;
}
/* DebugDraw::acquire allocates SSBOs even with WITH_DRAW_DEBUG disabled.
* WebGL2 cannot provide those optional diagnostic buffers. */
#else
Context *ctx = GPUBackend::get()->context_alloc(ghost_window, ghost_context);
GPU_context_active_set(wrap(ctx));
draw::DebugDraw::get().acquire();
#endif
return wrap(ctx);
}
@@ -215,7 +249,21 @@ void GPU_context_discard(GPUContext *ctx_)
Context *ctx = unwrap(ctx_);
BLI_assert(active_ctx == ctx);
#ifdef WITH_WEBGL_BACKEND
/* Registry/compiler lifetime must end before the final canvas context/backend is released. */
bool last_context;
{
std::scoped_lock lock(backend_users_mutex);
last_context = num_backend_users == 1;
}
if (last_context) {
GPU_exit();
}
#endif
#ifndef WITH_WEBGL_BACKEND
draw::DebugDraw::get().release();
#endif
GPUBackend *backend = GPUBackend::get();
/* Flush any remaining printf while making sure we are inside render boundaries. */
@@ -240,6 +288,9 @@ void GPU_context_discard(GPUContext *ctx_)
void GPU_context_active_set(GPUContext *ctx_)
{
Context *ctx = unwrap(ctx_);
#ifdef WITH_WEBGL_BACKEND
Context *previous = active_ctx;
#endif
if (active_ctx) {
GPU_shader_unbind();
@@ -249,7 +300,20 @@ void GPU_context_active_set(GPUContext *ctx_)
active_ctx = ctx;
if (ctx) {
#ifdef WITH_WEBGL_BACKEND
try {
ctx->activate();
}
catch (...) {
active_ctx = previous;
if (previous) {
previous->activate();
}
throw;
}
#else
ctx->activate();
#endif
/* It can happen that the previous context drew with a different color-space.
* In the case where the new context is drawing with the same shader that was previously bound
* (shader binding optimization), the uniform would not be set again because the dirty flag
@@ -265,6 +329,11 @@ GPUContext *GPU_context_active_get()
return wrap(Context::get());
}
uint64_t GPU_context_active_id_get()
{
return active_ctx ? active_ctx->context_id : uint64_t(-1);
}
void GPU_context_begin_frame(GPUContext *ctx)
{
gpu::Context *_ctx = unwrap(ctx);
@@ -295,7 +364,11 @@ void GPU_context_debug_pipeline_creation(GPUContext *ctx, bool enable)
* Used to avoid crash on some old drivers.
* \{ */
#if defined(__EMSCRIPTEN__) && !defined(__EMSCRIPTEN_PTHREADS__)
static std::recursive_mutex main_context_mutex;
#else
static Mutex main_context_mutex;
#endif
void GPU_context_main_lock()
{
@@ -451,7 +524,11 @@ static const char *gpu_backend_type_name(const GPUBackendType backend_type)
{
switch (backend_type) {
case GPU_BACKEND_OPENGL:
#ifdef WITH_WEBGL_BACKEND
return "WebGL2";
#else
return "OpenGL";
#endif
case GPU_BACKEND_VULKAN:
return "Vulkan";
case GPU_BACKEND_METAL:
@@ -478,7 +555,7 @@ bool GPU_backend_type_selection_detect()
if (g_backend_type_override.has_value()) {
backends_to_check.add(*g_backend_type_override);
}
#if defined(WITH_OPENGL_BACKEND)
#if defined(WITH_OPENGL_BACKEND) || defined(WITH_WEBGL_BACKEND)
backends_to_check.add(GPU_BACKEND_OPENGL);
#elif defined(WITH_METAL_BACKEND)
backends_to_check.add(GPU_BACKEND_METAL);
@@ -512,7 +589,11 @@ static bool gpu_backend_supported()
{
switch (g_backend_type) {
case GPU_BACKEND_OPENGL:
#ifdef WITH_OPENGL_BACKEND
#ifdef WITH_WEBGL_BACKEND
/* WM selects the backend before creating its first GHOST window. The actual
* WebGL2 context is checked by WebGLBackend and context_alloc after creation. */
return true;
#elif defined(WITH_OPENGL_BACKEND)
return true;
#else
return false;
@@ -551,7 +632,11 @@ static void gpu_backend_create()
BLI_assert(GPU_backend_supported());
switch (g_backend_type) {
#ifdef WITH_OPENGL_BACKEND
#ifdef WITH_WEBGL_BACKEND
case GPU_BACKEND_OPENGL:
g_backend = MEM_new<WebGLBackend>(__func__);
break;
#elif defined(WITH_OPENGL_BACKEND)
case GPU_BACKEND_OPENGL:
g_backend = MEM_new<GLBackend>(__func__);
break;
@@ -597,7 +682,11 @@ void gpu_backend_discard()
GPUBackendType GPU_backend_get_type()
{
#ifdef WITH_OPENGL_BACKEND
#ifdef WITH_WEBGL_BACKEND
if (g_backend && dynamic_cast<WebGLBackend *>(g_backend) != nullptr) {
return GPU_BACKEND_OPENGL;
}
#elif defined(WITH_OPENGL_BACKEND)
if (g_backend && dynamic_cast<GLBackend *>(g_backend) != nullptr) {
return GPU_BACKEND_OPENGL;
}
@@ -639,7 +728,10 @@ namespace gpu {
static GHOST_TDrawingContextType ghost_context_type()
{
switch (GPU_backend_type_selection_get()) {
#ifdef WITH_OPENGL_BACKEND
#ifdef WITH_WEBGL_BACKEND
case GPU_BACKEND_OPENGL:
return GHOST_kDrawingContextTypeWebGL;
#elif defined(WITH_OPENGL_BACKEND)
case GPU_BACKEND_OPENGL:
return GHOST_kDrawingContextTypeOpenGL;
#endif

View File

@@ -8,6 +8,8 @@
#include "MEM_guardedalloc.h"
#include <memory>
#include "BLI_math_base.h"
#include "BLI_string.h"
#include "BLI_utildefines.h"
@@ -137,6 +139,18 @@ void FrameBuffer::attachment_remove(GPUAttachmentType type)
void FrameBuffer::subpass_transition(const GPUAttachmentState depth_attachment_state,
Span<GPUAttachmentState> color_attachment_states)
{
#ifdef __EMSCRIPTEN__
/* The browser's default color attachment has no Texture wrapper. Route it explicitly
* instead of treating it as an absent attachment and clearing its write bit. */
Context *context = Context::get();
if (this == context->back_left || this == context->back_right) {
BLI_assert(depth_attachment_state == GPU_ATTACHMENT_IGNORE);
BLI_assert(color_attachment_states.size() == 1);
color_attachments_bits_ = color_attachment_states[0] == GPU_ATTACHMENT_WRITE ? 1 : 0;
subpass_transition_impl(depth_attachment_state, color_attachment_states);
return;
}
#endif
/* NOTE: Depth is not supported as input attachment because the Metal API doesn't support it and
* because depth is not compatible with the framebuffer fetch implementation. */
BLI_assert(depth_attachment_state != GPU_ATTACHMENT_READ);
@@ -171,6 +185,19 @@ void FrameBuffer::load_store_config_array(const GPULoadStore *load_store_actions
Span<GPULoadStore> color_attachment_actions(load_store_actions + 1, actions_len - 1);
BLI_assert(color_attachment_actions.size() <= GPU_FB_MAX_COLOR_ATTACHMENT);
#ifdef __EMSCRIPTEN__
/* Window composition uses the implicit browser color buffer, not a texture attachment.
* Depth/stencil are unused by this pass; keep their unsupported load/store contract explicit. */
Context *context = Context::get();
if (this == context->back_left || this == context->back_right) {
BLI_assert(actions_len == 2);
BLI_assert(depth_action.load_action == GPU_LOADACTION_DONT_CARE &&
depth_action.store_action == GPU_STOREACTION_DONT_CARE);
this->attachment_set_loadstore_op(GPU_FB_COLOR_ATTACHMENT0, color_attachment_actions[0]);
return;
}
#endif
if (!attachments_[GPU_FB_DEPTH_ATTACHMENT].tex &&
!attachments_[GPU_FB_DEPTH_STENCIL_ATTACHMENT].tex)
{
@@ -734,7 +761,8 @@ GPUOffScreen *GPU_offscreen_create(int width,
bool clear,
char err_out[256])
{
GPUOffScreen *ofs = MEM_new_zeroed<GPUOffScreen>(__func__);
std::unique_ptr<GPUOffScreen, decltype(&GPU_offscreen_free)> ofs(
MEM_new_zeroed<GPUOffScreen>(__func__), GPU_offscreen_free);
/* Sometimes areas can have 0 height or width and this will
* create a 1D texture which we don't want. */
@@ -766,19 +794,31 @@ GPUOffScreen *GPU_offscreen_create(int width,
else {
fprintf(stderr, "%s", error);
}
GPU_offscreen_free(ofs);
return nullptr;
}
gpu::FrameBuffer *fb = gpu_offscreen_fb_get(ofs);
gpu::FrameBuffer *fb = gpu_offscreen_fb_get(ofs.get());
/* check validity at the very end! */
if (!GPU_framebuffer_check_valid(fb, err_out)) {
GPU_offscreen_free(ofs);
return nullptr;
}
if (clear) {
#ifdef __EMSCRIPTEN__
/* Native WM region buffers (including headers and popup regions) start transparent.
* Express this as a full attachment load clear, independent of a previous region's
* scissor. The stored color is subsequently reused by partial redraw and compositing. */
const GPULoadStore actions[] = {
{with_depth_buffer ? GPU_LOADACTION_CLEAR : GPU_LOADACTION_DONT_CARE,
with_depth_buffer ? GPU_STOREACTION_STORE : GPU_STOREACTION_DONT_CARE,
{0.0, 0.0, 0.0, 0.0}},
{GPU_LOADACTION_CLEAR, GPU_STOREACTION_STORE, {0.0, 0.0, 0.0, 0.0}},
};
GPU_framebuffer_bind_loadstore(fb, actions, ARRAY_SIZE(actions));
/* Editor callbacks use ordinary scissored clears, not explicit load/store passes. */
GPU_framebuffer_bind(fb);
#else
GPU_framebuffer_bind(fb);
if (with_depth_buffer) {
GPU_framebuffer_clear_color_depth(fb, {0.0, 0.0, 0.0, 0.0}, 0.0f);
@@ -786,10 +826,11 @@ GPUOffScreen *GPU_offscreen_create(int width,
else {
GPU_framebuffer_clear_color(fb, {0.0, 0.0, 0.0, 0.0});
}
#endif
}
GPU_framebuffer_restore();
return ofs;
return ofs.release();
}
void GPU_offscreen_free(GPUOffScreen *offscreen)

View File

@@ -300,6 +300,7 @@ void Immediate::polyline_draw_workaround(uint64_t offset)
int data[3] = {stride, int(imm->vertex_idx), int(offset / 4)};
GPU_shader_uniform_3iv(imm->shader, "gpu_vert_stride_count_offset", data);
GPU_shader_uniform_1b(imm->shader, "gpu_index_no_buffer", true);
GPU_shader_uniform_1i(imm->shader, "gpu_polyline_index_start", 0);
{
/* Setup attributes metadata uniforms. */

View File

@@ -23,6 +23,19 @@ namespace blender {
* (except for the extensions), I chose alphabetical and reverse alphabetical order
*/
static bool initialized = false;
static bool shader_resources_initialized = false;
void GPU_init_shader_resources()
{
if (shader_resources_initialized) {
return;
}
gpu_backend_init_resources();
gpu_shader_dependency_init();
gpu_shader_create_info_init();
GPU_pass_cache_init();
shader_resources_initialized = true;
}
void GPU_init()
{
@@ -31,22 +44,24 @@ void GPU_init()
return;
}
initialized = true;
gpu_backend_init_resources();
gpu_shader_dependency_init();
gpu_shader_create_info_init();
GPU_init_shader_resources();
#ifndef WITH_WEBGL_BACKEND
/* Browser resources are canvas-owned. Compile supported shaders lazily in their draw context. */
GPU_shader_builtin_warm_up();
GPU_pass_cache_init();
#endif
gpu_batch_init();
initialized = true;
}
void GPU_exit()
{
gpu_batch_exit();
if (!shader_resources_initialized) {
return;
}
if (initialized) {
gpu_batch_exit();
}
GPU_pass_cache_free();
@@ -59,6 +74,7 @@ void GPU_exit()
gpu_shader_create_info_exit();
initialized = false;
shader_resources_initialized = false;
}
bool GPU_is_init()

View File

@@ -41,6 +41,9 @@ class QueryPool {
* drawn.
*/
virtual void get_occlusion_result(MutableSpan<uint32_t> r_values) = 0;
/** Nonblocking availability probe; desktop pools retain synchronous behavior. */
virtual bool occlusion_result_ready() { return true; }
};
} // namespace blender::gpu

View File

@@ -10,6 +10,7 @@
*/
#include <cstdlib>
#include <cstring>
#include <stdexcept>
#include "GPU_select.hh"
@@ -19,6 +20,10 @@
#include "gpu_select_private.hh"
#ifdef WITH_WEBGL_BACKEND
# include "webgl_backend.hh"
#endif
namespace blender {
/* -------------------------------------------------------------------- */
@@ -135,12 +140,24 @@ static void gpu_select_begin_ex(GPUSelectBuffer *buffer,
void GPU_select_begin_next(
GPUSelectBuffer *buffer, const rcti *input, const int radius, GPUSelectMode mode, int oldhits)
{
gpu_select_begin_ex(buffer, input, radius, mode, oldhits, true);
try {
gpu_select_begin_ex(buffer, input, radius, mode, oldhits, true);
}
catch (...) {
try { GPU_select_cache_end(); } catch (...) {}
throw;
}
}
void GPU_select_begin(GPUSelectBuffer *buffer, const rcti *input, GPUSelectMode mode, int oldhits)
{
gpu_select_begin_ex(buffer, input, 0, mode, oldhits, false);
try {
gpu_select_begin_ex(buffer, input, 0, mode, oldhits, false);
}
catch (...) {
try { GPU_select_cache_end(); } catch (...) {}
throw;
}
}
bool GPU_select_load_id(uint id)
@@ -166,29 +183,63 @@ bool GPU_select_load_id(uint id)
}
}
GPUSelectQueryAsync *GPU_select_query_submit()
{
if (!g_select_state.select_is_active || g_select_state.algorithm != ALGO_SAMPLE_QUERY) {
throw std::runtime_error("Detached selection requires an active sample query");
}
try {
GPUSelectQueryAsync *query = gpu_select_query_detach();
g_select_state.select_is_active = false;
return query;
}
catch (...) {
try { GPU_select_cache_end(); } catch (...) {}
throw;
}
}
uint GPU_select_end()
{
uint hits = 0;
switch (g_select_state.algorithm) {
case ALGO_SELECT_NEXT: {
hits = gpu_select_next_end();
break;
}
case ALGO_SAMPLE_QUERY: {
hits = gpu_select_query_end();
break;
}
default: /* ALGO_DEPTH_PICK */
{
hits = gpu_select_pick_end();
break;
}
if (!g_select_state.select_is_active) {
throw std::runtime_error("NATIVE_GPU_SELECTION_CANCELLED: selection is no longer active");
}
try {
uint hits = 0;
g_select_state.select_is_active = false;
switch (g_select_state.algorithm) {
case ALGO_SELECT_NEXT: {
hits = gpu_select_next_end();
break;
}
case ALGO_SAMPLE_QUERY: {
hits = gpu_select_query_end();
break;
}
default: /* ALGO_DEPTH_PICK */
{
hits = gpu_select_pick_end();
break;
}
}
return hits;
#ifdef WITH_WEBGL_BACKEND
/* Includes CPU-cache replay, which never enters the GPU readback interrupt
* checkpoints. The editor's exception boundary rolls back this query's hits. */
if (g_select_state.algorithm != ALGO_SAMPLE_QUERY) {
/* Sample queries check after readback/restoration, before committing their
* result transaction. Do not cancel after releasing that rollback owner. */
gpu::webgl_select_check_interrupt();
}
#endif
g_select_state.select_is_active = false;
return hits;
}
catch (...) {
try { GPU_select_cache_end(); } catch (...) {}
throw;
}
}
/** \} */
@@ -213,6 +264,9 @@ void GPU_select_cache_begin()
void GPU_select_cache_load_id()
{
if (!GPU_select_cache_revalidate()) {
throw std::runtime_error("NATIVE_GPU_SELECTION_CANCELLED: selection cache context retired");
}
BLI_assert(g_select_state.use_cache == true);
if (g_select_state.algorithm == ALGO_DEPTH_PICK) {
gpu_select_pick_cache_load_id();
@@ -221,9 +275,26 @@ void GPU_select_cache_load_id()
void GPU_select_cache_end()
{
if (g_select_state.algorithm == ALGO_DEPTH_PICK) {
BLI_assert(g_select_state.use_cache == true);
if (g_select_state.algorithm == ALGO_SAMPLE_QUERY && g_select_state.select_is_active) {
/* Query begin/draw/readback can fail before end, including context loss.
* Release the pool and editor result owner before another gesture starts. */
g_select_state.select_is_active = false;
gpu_select_query_cancel();
}
if (g_select_state.algorithm == ALGO_SELECT_NEXT && g_select_state.select_is_active) {
/* A failed draw can leave before GPU_select_end(). The next engine retains
* the editor-owned result buffer until end, so cancellation/context teardown
* must roll back its results and release that reference and the cache flags.
* This is CPU-only and safe after the browser has lost its drawing context. */
gpu_select_next_cancel();
g_select_state.select_is_active = false;
}
if (g_select_state.algorithm == ALGO_DEPTH_PICK &&
(g_select_state.use_cache || g_select_state.select_is_active))
{
/* Cleanup can run both at the failed editor boundary and context teardown. */
gpu_select_pick_cache_end();
g_select_state.select_is_active = false;
}
g_select_state.use_cache = false;
/* Paranoid assignment, should already be false. */
@@ -232,7 +303,24 @@ void GPU_select_cache_end()
bool GPU_select_is_cached()
{
return g_select_state.use_cache && gpu_select_pick_is_cached();
if (!g_select_state.use_cache) {
return false;
}
if (gpu_select_pick_is_cached()) {
return true;
}
/* Retire both the algorithm's CPU allocations and the dispatch flags. The
* View3D caller then redraws instead of replaying IDs from a lost context. */
GPU_select_cache_end();
return false;
}
bool GPU_select_cache_revalidate()
{
/* This delegates to the WebGL-owned lifetime closure used by the pick
* cache. A restored browser context therefore retires stale IDs before a
* native WM frame dispatches its next View3D gesture. */
return GPU_select_is_cached();
}
/** \} */

View File

@@ -8,9 +8,11 @@
* Glue to make the new Select-Next engine work with the old GPU select API.
*/
#include <cfloat>
#include <stdexcept>
#include "BLI_rect.h"
#include "BLI_span.hh"
#include "BLI_utildefines.h"
#include "gpu_select_private.hh"
@@ -19,6 +21,9 @@ namespace blender {
struct GPUSelectNextState {
/** Result buffer set on initialization. */
GPUSelectBuffer *buffer = nullptr;
uint64_t token = 0;
int64_t result_start = 0;
bool published = false;
/** Area of the viewport to render / select from. */
rcti rect = {0, 0, 0, 0};
/** The radius relative to the center of `rect` in which to select. Ignored if 0. */
@@ -30,6 +35,7 @@ struct GPUSelectNextState {
};
static GPUSelectNextState g_state = {};
static uint64_t next_token = 0;
void gpu_select_next_begin(GPUSelectBuffer *buffer,
const rcti *input,
@@ -37,10 +43,24 @@ void gpu_select_next_begin(GPUSelectBuffer *buffer,
GPUSelectMode mode)
{
if (g_state.buffer || !buffer ||
!ELEM(mode, GPU_SELECT_ALL, GPU_SELECT_PICK_ALL, GPU_SELECT_PICK_NEAREST))
{
throw std::runtime_error("Invalid or overlapping native selection transaction");
}
/* Zero always denotes an inactive producer, including after cancellation. */
if (++next_token == 0) {
++next_token;
}
g_state.token = next_token;
g_state.buffer = buffer;
g_state.result_start = buffer->storage.size();
g_state.published = false;
g_state.rect = *input;
g_state.mode = mode;
g_state.radius = radius;
/* A failed/empty draw must not reuse the preceding region's hit count. */
g_state.hits = 0;
}
int2 gpu_select_next_get_pick_area_center()
@@ -58,8 +78,24 @@ int gpu_select_next_get_radius()
return g_state.radius;
}
void gpu_select_next_set_result(GPUSelectResult *hit_buf, uint hit_len)
uint64_t gpu_select_next_get_token()
{
return g_state.token;
}
void gpu_select_next_validate_token(uint64_t token)
{
if (!token || token != g_state.token || !g_state.buffer) {
throw std::runtime_error("Native selection result belongs to a cancelled draw");
}
}
void gpu_select_next_set_result(uint64_t token, GPUSelectResult *hit_buf, uint hit_len)
{
gpu_select_next_validate_token(token);
if (g_state.published || (hit_len && !hit_buf)) {
throw std::runtime_error("Invalid or duplicate native selection result");
}
const int old_size = g_state.buffer->storage.size();
g_state.buffer->storage.resize(old_size + hit_len);
MutableSpan<GPUSelectResult> hit_results = g_state.buffer->storage.as_mutable_span().slice(
@@ -85,11 +121,31 @@ void gpu_select_next_set_result(GPUSelectResult *hit_buf, uint hit_len)
}
g_state.hits = hit_len;
g_state.published = true;
}
uint gpu_select_next_end()
{
return g_state.hits;
gpu_select_next_validate_token(g_state.token);
if (!g_state.published) {
gpu_select_next_cancel();
throw std::runtime_error("Native selection draw ended without a result");
}
const uint hits = g_state.hits;
/* The editor owns this buffer, often on its stack. Do not retain that
* address after the draw transaction, including its exception cleanup. */
g_state = {};
return hits;
}
void gpu_select_next_cancel()
{
/* Preserve entries owned by earlier queries while discarding this draw's
* publication. No GPU access: context-loss cleanup must remain possible. */
if (g_state.buffer && g_state.buffer->storage.size() > g_state.result_start) {
g_state.buffer->storage.resize(g_state.result_start);
}
g_state = {};
}
} // namespace blender

View File

@@ -11,6 +11,11 @@
#include <cfloat>
#include <cstdlib>
#include <cstring>
#include <stdexcept>
#ifdef WITH_WEBGL_BACKEND
# include "webgl_backend.hh"
#endif
#include "GPU_debug.hh"
#include "GPU_framebuffer.hh"
@@ -232,6 +237,9 @@ struct GPUPickState {
GPUSelectBuffer *buffer;
/** Mode of this operation. */
GPUSelectMode mode;
#ifdef WITH_WEBGL_BACKEND
std::function<bool()> context_is_valid;
#endif
/** GPU drawing, never use when `is_cached == true`. */
struct {
@@ -295,10 +303,28 @@ struct GPUPickState {
static GPUPickState g_pick_state{};
static void gpu_select_pick_check_interrupt()
{
#ifdef WITH_WEBGL_BACKEND
gpu::webgl_select_check_interrupt();
if (!g_pick_state.context_is_valid || !g_pick_state.context_is_valid()) {
throw std::runtime_error("NATIVE_GPU_SELECTION_CANCELLED: selection context retired");
}
#endif
}
void gpu_select_pick_begin(GPUSelectBuffer *buffer, const rcti *input, GPUSelectMode mode)
{
GPUPickState *ps = &g_pick_state;
#ifdef WITH_WEBGL_BACKEND
gpu::webgl_select_check_interrupt();
if (!ps->is_cached) {
ps->context_is_valid = gpu::webgl_select_cache_validity_capture();
}
gpu_select_pick_check_interrupt();
#endif
#ifdef DEBUG_PRINT
printf("%s: mode=%d, use_cache=%d, is_cache=%d\n",
__func__,
@@ -331,14 +357,13 @@ void gpu_select_pick_begin(GPUSelectBuffer *buffer, const rcti *input, GPUSelect
* these to have the correct distance information. */
GPU_depth_test(GPU_DEPTH_LESS_EQUAL);
float viewport[4];
GPU_viewport_size_get_f(viewport);
GPU_viewport_size_get_i(ps->viewport);
ps->src.clip_rect = *input;
ps->src.rect_len = rect_len;
ps->gpu.clip_readpixels[0] = int(viewport[0]);
ps->gpu.clip_readpixels[1] = int(viewport[1]);
ps->gpu.clip_readpixels[0] = ps->viewport[0];
ps->gpu.clip_readpixels[1] = ps->viewport[1];
ps->gpu.clip_readpixels[2] = BLI_rcti_size_x(&ps->src.clip_rect);
ps->gpu.clip_readpixels[3] = BLI_rcti_size_y(&ps->src.clip_rect);
@@ -538,6 +563,7 @@ bool gpu_select_pick_load_id(uint id, bool end)
uint gpu_select_pick_end()
{
GPUPickState *ps = &g_pick_state;
gpu_select_pick_check_interrupt();
#ifdef DEBUG_PRINT
printf("%s\n", __func__);
@@ -658,7 +684,16 @@ uint gpu_select_pick_end()
/* Leave sorting up to the caller. */
qsort(depth_data, depth_data_len, sizeof(DepthID), depth_cmp);
g_pick_state.buffer->storage.reserve(g_pick_state.buffer->storage.size() + depth_data_len);
/* Sorting/replay can run while the UI thread cancels the gesture. Do not turn
* an interrupted cached pick into either selection or intentional deselection. */
try {
gpu_select_pick_check_interrupt();
g_pick_state.buffer->storage.reserve(g_pick_state.buffer->storage.size() + depth_data_len);
}
catch (...) {
MEM_delete(depth_data);
throw;
}
for (uint i = 0; i < depth_data_len; i++) {
#ifdef DEBUG_PRINT
printf(" hit: %u: depth %u\n", depth_data[i].id, depth_data[i].depth);
@@ -687,6 +722,7 @@ uint gpu_select_pick_end()
ps->is_cached = true;
}
ps->buffer = nullptr;
return hits;
}
@@ -717,21 +753,46 @@ void gpu_select_pick_cache_end()
g_pick_state.is_cached = false;
g_pick_state.cache.bufs.free_no_destruct();
/* A cancelled read may not reach pick_end. These buffers are not yet in
* the retained cache; release them without reading GPU state or publishing
* hits, including when the browser context has already been lost. */
MEM_SAFE_DELETE(g_pick_state.gpu.rect_depth);
MEM_SAFE_DELETE(g_pick_state.gpu.rect_depth_test);
if (g_pick_state.mode == GPU_SELECT_PICK_ALL) {
MEM_SAFE_DELETE(g_pick_state.all.hits);
g_pick_state.all.hits_len = 0;
g_pick_state.all.hits_len_alloc = 0;
}
else if (g_pick_state.mode == GPU_SELECT_PICK_NEAREST) {
MEM_SAFE_DELETE(g_pick_state.nearest.rect_id);
}
g_pick_state.gpu.is_init = false;
g_pick_state.buffer = nullptr;
#ifdef WITH_WEBGL_BACKEND
g_pick_state.context_is_valid = {};
#endif
}
bool gpu_select_pick_is_cached()
{
#ifdef WITH_WEBGL_BACKEND
return g_pick_state.is_cached && g_pick_state.context_is_valid &&
g_pick_state.context_is_valid();
#else
return g_pick_state.is_cached;
#endif
}
void gpu_select_pick_cache_load_id()
{
gpu_select_pick_check_interrupt();
BLI_assert(g_pick_state.is_cached == true);
GPUPickState *ps = &g_pick_state;
#ifdef DEBUG_PRINT
printf("%s (building depth from cache)\n", __func__);
#endif
for (DepthBufCache &rect_depth : ps->cache.bufs) {
gpu_select_pick_check_interrupt();
if (rect_depth.next != nullptr) {
/* We know the buffers differ, but this sub-region may not.
* Double check before adding an id-pass. */
@@ -748,6 +809,7 @@ void gpu_select_pick_cache_load_id()
}
}
}
gpu_select_pick_check_interrupt();
}
/** \} */

View File

@@ -10,6 +10,8 @@
#pragma once
#include <cstdint>
#include "BLI_math_vector_types.hh"
#include "GPU_select.hh"
@@ -37,6 +39,8 @@ void gpu_select_query_begin(GPUSelectBuffer *buffer,
int oldhits);
bool gpu_select_query_load_id(uint id);
uint gpu_select_query_end();
void gpu_select_query_cancel();
GPUSelectQueryAsync *gpu_select_query_detach();
/* gpu_select_next */
@@ -45,6 +49,10 @@ void gpu_select_next_begin(GPUSelectBuffer *buffer,
int radius,
GPUSelectMode mode);
uint gpu_select_next_end();
void gpu_select_next_cancel();
/** Identify the draw transaction across backend readback and context cancellation. */
uint64_t gpu_select_next_get_token();
void gpu_select_next_validate_token(uint64_t token);
/**
* Returns the center relative to the corner of the rect stored in the GPUSelectNextState.
@@ -52,7 +60,7 @@ uint gpu_select_next_end();
int2 gpu_select_next_get_pick_area_center();
GPUSelectMode gpu_select_next_get_mode();
int gpu_select_next_get_radius();
void gpu_select_next_set_result(GPUSelectResult *hit_buf, uint hit_len);
void gpu_select_next_set_result(uint64_t token, GPUSelectResult *hit_buf, uint hit_len);
#define SELECT_ID_NONE ((uint)0xffffffff)

View File

@@ -10,11 +10,16 @@
*/
#include <cstdlib>
#include <functional>
#include <exception>
#include <stdexcept>
#include <utility>
#include "GPU_debug.hh"
#include "GPU_framebuffer.hh"
#include "GPU_select.hh"
#include "GPU_state.hh"
#include "GPU_state_snapshot.hh"
#include "BLI_rect.h"
@@ -25,12 +30,15 @@
#include "gpu_query.hh"
#include "gpu_select_private.hh"
#ifdef WITH_WEBGL_BACKEND
# include "webgl_backend.hh"
#endif
namespace blender {
using namespace blender::gpu;
struct GPUSelectQueryState {
struct GPUSelectQueryAsync {
/** Tracks whether a query has been issued so that gpu_load_id can end the previous one. */
bool query_issued;
/** GPU queries abstraction. Contains an array of queries. */
@@ -39,6 +47,10 @@ struct GPUSelectQueryState {
Vector<uint, QUERY_MIN_LEN> *ids;
/** Cache on initialization. */
GPUSelectBuffer *buffer;
GPUSelectBuffer *result_before;
StateSnapshot *pipeline;
std::function<bool()> owner_valid;
bool debug_group;
/** Mode of operation. */
GPUSelectMode mode;
uint index;
@@ -47,18 +59,69 @@ struct GPUSelectQueryState {
/** Previous state to restore after drawing. */
int viewport[4];
int scissor[4];
GPUWriteMask write_mask;
GPUDepthTest depth_test;
};
using GPUSelectQueryState = GPUSelectQueryAsync;
static GPUSelectQueryState g_query_state = {false};
/* Detach the transaction first. Repeated editor/context cleanup must neither
* end another query nor keep a pointer to a destroyed editor result buffer. */
static void gpu_select_query_release(const bool rollback)
{
GPUSelectQueryState state = std::move(g_query_state);
g_query_state = {};
if (rollback && state.buffer && state.result_before) {
std::swap(state.buffer->storage, state.result_before->storage);
}
delete state.queries;
delete state.ids;
delete state.result_before;
delete state.pipeline;
}
static void gpu_select_query_restore()
{
if (g_query_state.owner_valid && !g_query_state.owner_valid()) {
throw std::runtime_error("Native selection query context retired before publication");
}
std::exception_ptr failure;
if (g_query_state.pipeline) {
try { g_query_state.pipeline->restore(); }
catch (...) { failure = std::current_exception(); }
try {
GPU_viewport(UNPACK4(g_query_state.viewport));
GPU_scissor(UNPACK4(g_query_state.scissor));
}
catch (...) { if (!failure) { failure = std::current_exception(); } }
}
if (g_query_state.debug_group) {
g_query_state.debug_group = false;
try { GPU_debug_group_end(); }
catch (...) { if (!failure) { failure = std::current_exception(); } }
}
if (failure) { std::rethrow_exception(failure); }
}
void gpu_select_query_cancel()
{
/* The pool destructor ends only its own live query. No GL restoration is
* attempted against a replacement context; the editor schedules a redraw. */
try { gpu_select_query_restore(); } catch (...) {}
gpu_select_query_release(true);
}
void gpu_select_query_begin(GPUSelectBuffer *buffer,
const rcti *input,
const GPUSelectMode mode,
int oldhits)
{
GPU_debug_group_begin("Selection Queries");
BLI_assert(!g_query_state.buffer);
if (mode == GPU_SELECT_NEAREST_SECOND_PASS &&
(oldhits < 0 || oldhits > buffer->storage.size()))
{
throw std::runtime_error("Selection second pass requires a valid first-pass result range");
}
g_query_state.query_issued = false;
g_query_state.buffer = buffer;
@@ -66,15 +129,20 @@ void gpu_select_query_begin(GPUSelectBuffer *buffer,
g_query_state.index = 0;
g_query_state.oldhits = oldhits;
g_query_state.result_before = new GPUSelectBuffer(*buffer);
#ifdef WITH_WEBGL_BACKEND
g_query_state.owner_valid = webgl_select_cache_validity_capture();
#endif
GPU_scissor_get(g_query_state.scissor);
GPU_viewport_size_get_i(g_query_state.viewport);
g_query_state.pipeline = new StateSnapshot();
GPU_debug_group_begin("Selection Queries");
g_query_state.debug_group = true;
g_query_state.ids = new Vector<uint, QUERY_MIN_LEN>();
g_query_state.queries = GPUBackend::get()->querypool_alloc();
g_query_state.queries->init(GPU_QUERY_OCCLUSION);
g_query_state.write_mask = GPU_write_mask_get();
g_query_state.depth_test = GPU_depth_test_get();
GPU_scissor_get(g_query_state.scissor);
GPU_viewport_size_get_i(g_query_state.viewport);
/* Write to color buffer. Seems to fix issues with selecting alpha blended geom (see #7997). */
GPU_color_mask(true, true, true, true);
@@ -113,10 +181,11 @@ bool gpu_select_query_load_id(uint id)
{
if (g_query_state.query_issued) {
g_query_state.queries->end_query();
g_query_state.query_issued = false;
}
g_query_state.queries->begin_query();
g_query_state.ids->append(id);
g_query_state.queries->begin_query();
g_query_state.query_issued = true;
if (g_query_state.mode == GPU_SELECT_NEAREST_SECOND_PASS) {
@@ -134,48 +203,95 @@ bool gpu_select_query_load_id(uint id)
return true;
}
GPUSelectQueryAsync *gpu_select_query_detach()
{
if (g_query_state.query_issued) {
g_query_state.queries->end_query();
g_query_state.query_issued = false;
}
gpu_select_query_restore();
delete g_query_state.pipeline;
g_query_state.pipeline = nullptr;
auto *query = new GPUSelectQueryAsync(std::move(g_query_state));
g_query_state = {};
return query;
}
void GPU_select_query_dispose(GPUSelectQueryAsync *&query)
{
if (!query) { return; }
/* No restoration: a later WM frame owns the current drawing state. */
delete query->queries;
delete query->ids;
delete query->result_before;
delete query->pipeline;
delete query;
query = nullptr;
}
static uint gpu_select_query_publish(GPUSelectQueryAsync &state, Span<uint32_t> result)
{
uint hits = 0;
for (int i = 0; i < result.size(); i++) {
if (result[i] == 0) { continue; }
if (state.mode != GPU_SELECT_NEAREST_SECOND_PASS) {
state.buffer->storage.append({(*state.ids)[i], 0xFFFF});
hits++;
}
else {
for (int j = 0; j < state.oldhits; j++) {
if (state.buffer->storage[j].id == (*state.ids)[i]) {
state.buffer->storage[j].depth = 0;
}
}
break;
}
}
return hits;
}
bool GPU_select_query_poll(GPUSelectQueryAsync *query, uint &r_hits)
{
if (!query || !query->queries || (query->owner_valid && !query->owner_valid())) {
throw std::runtime_error("NATIVE_GPU_SELECTION_CANCELLED: detached query owner retired");
}
if (!query->queries->occlusion_result_ready()) { return false; }
Vector<uint32_t, QUERY_MIN_LEN> result(query->ids->size());
query->queries->get_occlusion_result(result);
#ifdef WITH_WEBGL_BACKEND
webgl_select_check_interrupt();
#endif
try { r_hits = gpu_select_query_publish(*query, result); }
catch (...) {
std::swap(query->buffer->storage, query->result_before->storage);
throw;
}
return true;
}
uint gpu_select_query_end()
{
uint hits = 0;
if (g_query_state.query_issued) {
g_query_state.queries->end_query();
g_query_state.query_issued = false;
}
Span<uint> ids = *g_query_state.ids;
Vector<uint32_t, QUERY_MIN_LEN> result(ids.size());
g_query_state.queries->get_occlusion_result(result);
for (int i = 0; i < result.size(); i++) {
if (result[i] != 0) {
if (g_query_state.mode != GPU_SELECT_NEAREST_SECOND_PASS) {
GPUSelectResult hit_result{};
hit_result.id = ids[i];
hit_result.depth = 0xFFFF;
g_query_state.buffer->storage.append(hit_result);
hits++;
}
else {
int j;
/* search in buffer and make selected object first */
for (j = 0; j < g_query_state.oldhits; j++) {
if (g_query_state.buffer->storage[j].id == ids[i]) {
g_query_state.buffer->storage[j].depth = 0;
}
}
break;
}
}
}
/* Restore and check cancellation before publishing either appended IDs or
* the second-pass changes to existing depths. Cancel retains a full backup. */
gpu_select_query_restore();
#ifdef WITH_WEBGL_BACKEND
webgl_select_check_interrupt();
#endif
delete g_query_state.queries;
delete g_query_state.ids;
hits = gpu_select_query_publish(g_query_state, result);
GPU_write_mask(g_query_state.write_mask);
GPU_depth_test(g_query_state.depth_test);
GPU_viewport(UNPACK4(g_query_state.viewport));
GPU_debug_group_end();
gpu_select_query_release(false);
return hits;
}

View File

@@ -29,6 +29,7 @@
#include "gpu_shader_metadata_private.hh"
#include "gpu_shader_private.hh"
#include <filesystem>
#include <string>
@@ -220,7 +221,15 @@ gpu::Shader *GPU_shader_create_from_info_name(const char *info_name)
std::cerr << "Warning: Trying to compile \"" << info.name_
<< "\" which was not marked for static compilation.\n";
}
return GPU_shader_create_from_info(_info);
gpu::Shader *shader = GPU_shader_create_from_info(_info);
#ifdef WITH_WEBGL_BACKEND
/* Native draw callers assume builtin compilation succeeds. Propagate an
* unsupported browser shader to the frame boundary before they dereference it. */
if (!shader) {
throw std::runtime_error(std::string("Blender WebGL shader unavailable: ") + info_name);
}
#endif
return shader;
}
gpu::Shader *GPU_shader_create_from_info(const GPUShaderCreateInfo *_info)
@@ -387,6 +396,12 @@ void GPU_shader_bind(gpu::Shader *gpu_shader,
Context *ctx = Context::get();
#ifdef WITH_WEB
/* WebGPU compilation, specialization and uniform setup may throw. Do not
* cache a failed binding: the next region redraw must retry the complete
* native bind even when it selects this same shader. */
try {
#endif
if (ctx->shader != shader) {
ctx->shader = shader;
shader->bind(constants_state);
@@ -412,6 +427,13 @@ void GPU_shader_bind(gpu::Shader *gpu_shader,
GPU_storagebuf_bind(ctx->printf_buf.last(), GPU_SHADER_PRINTF_SLOT);
}
#endif
#ifdef WITH_WEB
}
catch (...) {
ctx->shader = nullptr;
throw;
}
#endif
}
void GPU_shader_unbind()
@@ -806,7 +828,9 @@ Shader *ShaderCompiler::compile(const shader::ShaderCreateInfo &orig_info, bool
CLOG_DEBUG(&LOG, "Compiling Shader \"%s\"", orig_info.name_.c_str());
Shader *shader = GPUBackend::get()->shader_alloc(orig_info.name_.c_str());
/* Backend context loss and source generation can fail before finalize. Retain ownership until
* compilation succeeds, including the create-info error return below. */
std::unique_ptr<Shader> shader(GPUBackend::get()->shader_alloc(orig_info.name_.c_str()));
ShaderCreateInfo specialized_info = orig_info;
@@ -974,8 +998,7 @@ Shader *ShaderCompiler::compile(const shader::ShaderCreateInfo &orig_info, bool
}
if (!shader->finalize(&info)) {
delete shader;
shader = nullptr;
shader.reset();
}
if (Context::get()) {
@@ -994,7 +1017,7 @@ Shader *ShaderCompiler::compile(const shader::ShaderCreateInfo &orig_info, bool
end_time.time_since_epoch().count());
}
return shader;
return shader.release();
}
static ThreadQueueWorkPriority to_work_priority(CompilationPriority priority)

View File

@@ -242,8 +242,8 @@ struct GPUSource {
shader::PrintfFormat::Block::ArgumentType type =
shader::PrintfFormat::Block::ArgumentType::NONE;
int64_t start = 0, end = 0, cursor = -1;
while ((end = format.find_first_of('%', cursor + 1)) != -1) {
size_t start = 0, end = 0, cursor = std::string::npos;
while ((end = format.find_first_of('%', cursor + 1)) != std::string::npos) {
if (end - start > 0) {
/* Add the previous block without the newly found % character. */
fmt.format_blocks.append({type, format.substr(start, end - start)});

View File

@@ -17,6 +17,16 @@
#include "BLI_utildefines.h"
#include "GPU_state.hh"
#include "GPU_state_snapshot.hh"
#include <exception>
#include <stdexcept>
#include <functional>
#include "GPU_framebuffer.hh"
#ifdef WITH_WEBGL_BACKEND
# include "webgl_backend.hh"
#endif
#include "gpu_backend.hh"
#include "gpu_context_private.hh"
@@ -27,6 +37,93 @@ namespace blender {
using namespace blender::gpu;
struct gpu::ResourceBindingSnapshot::Data {
Context *context;
std::function<void()> resume;
};
gpu::ResourceBindingSnapshot::ResourceBindingSnapshot()
: data_(std::make_unique<Data>(Data{Context::get(), {}}))
{
#ifdef WITH_WEBGL_BACKEND
data_->resume = webgl_resource_state_capture();
#endif
}
gpu::ResourceBindingSnapshot::~ResourceBindingSnapshot() = default;
void gpu::ResourceBindingSnapshot::restore() const
{
if (Context::get() != data_->context) {
throw std::runtime_error("GPU resource bindings restored in a different context");
}
if (data_->resume) { data_->resume(); }
}
struct gpu::StateSnapshot::Data {
Context *context;
GPUState state;
GPUStateMutable mutable_state;
FrameBuffer *framebuffer;
bool scissor_test;
std::function<void()> resume_framebuffer;
ResourceBindingSnapshot resources;
};
gpu::StateSnapshot::StateSnapshot()
{
Context *context = Context::get();
data_.reset(new Data{context,
context->state_manager->state,
context->state_manager->mutable_state,
context->active_fb,
context->active_fb->scissor_test_get(),
{},
{}});
#ifdef WITH_WEBGL_BACKEND
data_->resume_framebuffer = webgl_framebuffer_state_capture(context->active_fb);
#endif
}
gpu::StateSnapshot::~StateSnapshot() = default;
void gpu::StateSnapshot::restore() const
{
if (Context::get() != data_->context) {
throw std::runtime_error("GPU pipeline state restored in a different context");
}
/* Restore the native desired state, not raw GL state behind its cache. This
* includes masks, blending, stencil ops/reference, clipping, culling, FIRST,
* point size and line width. The next backend draw applies these values. */
data_->context->state_manager->state = data_->state;
data_->context->state_manager->mutable_state = data_->mutable_state;
data_->framebuffer->scissor_test_set(data_->scissor_test);
}
void gpu::StateSnapshot::restore_framebuffer() const
{
if (Context::get() != data_->context) {
throw std::runtime_error("GPU framebuffer state restored in a different context");
}
/* Restore resources even if framebuffer recovery fails; never leave the
* auxiliary shader/selection bindings installed while unwinding. */
std::exception_ptr failure;
try {
if (data_->resume_framebuffer) {
data_->resume_framebuffer();
}
else {
GPU_framebuffer_bind(data_->framebuffer);
}
}
catch (...) { failure = std::current_exception(); }
try {
data_->resources.restore();
}
catch (...) { if (!failure) { failure = std::current_exception(); } }
if (failure) { std::rethrow_exception(failure); }
}
#define SET_STATE(_prefix, _state, _value) \
do { \
StateManager *stack = Context::get()->state_manager; \
@@ -260,6 +357,11 @@ void GPU_scissor_get(int coords[4])
Context::get()->active_fb->scissor_get(coords);
}
bool GPU_polygon_smooth_get()
{
return bool(Context::get()->state_manager->state.polygon_smooth);
}
void GPU_viewport_size_get_f(float coords[4])
{
int viewport[4];

View File

@@ -8,6 +8,8 @@
#include "BLI_string.h"
#include <memory>
#include "DNA_userdef_types.h"
#include "GPU_framebuffer.hh"
@@ -264,7 +266,7 @@ static inline gpu::Texture *gpu_texture_create(const char *name,
eGPUDataFormat data_format = GPU_DATA_FLOAT)
{
BLI_assert(mip_len > 0);
Texture *tex = GPUBackend::get()->texture_alloc(name);
std::unique_ptr<Texture> tex(GPUBackend::get()->texture_alloc(name));
tex->usage_set(usage);
bool success = false;
@@ -289,13 +291,12 @@ static inline gpu::Texture *gpu_texture_create(const char *name,
}
if (!success) {
delete tex;
return nullptr;
}
if (pixels) {
tex->update(data_format, pixels);
}
return reinterpret_cast<gpu::Texture *>(tex);
return tex.release();
}
gpu::Texture *GPU_texture_create_1d(const char *name,
@@ -478,7 +479,7 @@ gpu::Texture *GPU_texture_create_view(const char *name,
"Source texture of TextureView must have GPU_TEXTURE_USAGE_FORMAT_VIEW usage "
"flag if view texture format is different.");
Texture *view = GPUBackend::get()->texture_alloc(name);
view->init_view(source_texture,
if (!view->init_view(source_texture,
view_format,
source_texture->type_get(),
mip_start,
@@ -486,7 +487,11 @@ gpu::Texture *GPU_texture_create_view(const char *name,
layer_start,
layer_len,
cube_as_array,
use_stencil);
use_stencil))
{
delete view;
return nullptr;
}
/* On integer textures, disable filtering by default, as this is not guaranteed to be
* consistently supported across backends. */

View File

@@ -18,6 +18,12 @@
#include "fmt/format.h"
#ifdef __EMSCRIPTEN__
# include "BLI_memory_utils.hh"
# include "../webgl/webgl_texture.hh"
# include <stdexcept>
#endif
namespace blender::gpu {
TexturePool &TexturePool::get()
@@ -51,6 +57,24 @@ Texture *TexturePoolImpl::acquire_texture_impl(int3 extent,
/* TODO(not_mark): this flag can likely be removed from TexturePoolImpl entirely. */
usage |= GPU_TEXTURE_USAGE_FORMAT_VIEW;
#ifdef __EMSCRIPTEN__
/* GP returns mask/layer/depth attachments after every draw. Browser restoration
* keeps their descriptors and this pool alive, but destroys their GL storage.
* Only idle owners can be discarded here; acquired owners still belong to the
* native caller. Pool contents are undefined on acquire, so allocate normally
* and let the original mask/depth passes initialize the replacement. */
const auto context = emscripten_webgl_get_current_context();
if (!Context::get() || context <= 0 || emscripten_is_webgl_context_lost(context)) {
throw std::runtime_error("Native texture pool acquisition requires a live WebGL context");
}
for (int64_t i = pool_.size() - 1; i >= 0; i--) {
if (!webgl_texture_has_live_storage(pool_[i].texture)) {
GPU_texture_free(pool_[i].texture);
pool_.remove_and_reorder(i);
}
}
#endif
/* Search pool for compatible available texture first. */
int64_t match_index = -1;
for (uint64_t i : pool_.index_range()) {
@@ -95,6 +119,15 @@ Texture *TexturePoolImpl::acquire_texture_impl(int3 extent,
/* Otherwise, allocate a new texture of the specified type. */
TextureHandle handle = {GPUBackend::get()->texture_alloc(name_str.c_str())};
#ifdef __EMSCRIPTEN__
/* Failed allocation must not enter acquired_ or leak an unowned texture.
* The GP caller can then release the other attachments and retry as a group. */
BLI_SCOPED_DEFER([&]() {
if (handle.texture) {
GPU_texture_free(handle.texture);
}
});
#endif
handle.texture->usage_set(usage);
bool init_result = false;
switch (type) {
@@ -117,11 +150,22 @@ Texture *TexturePoolImpl::acquire_texture_impl(int3 extent,
BLI_assert_unreachable();
break;
}
#ifdef __EMSCRIPTEN__
if (!init_result || !webgl_texture_has_live_storage(handle.texture)) {
throw std::runtime_error("Native WebGL pooled texture allocation failed");
}
#endif
UNUSED_VARS_NDEBUG(init_result);
BLI_assert(init_result);
acquired_.add(handle);
#ifdef __EMSCRIPTEN__
Texture *texture = handle.texture;
handle.texture = nullptr;
return texture;
#else
return handle.texture;
#endif
} // namespace blender::gpu
void TexturePoolImpl::release_texture(Texture *tex)

View File

@@ -9,6 +9,8 @@
*/
#include <cstring>
#include <memory>
#include <stdexcept>
#include "BLI_math_vector.h"
#include "BLI_math_vector_types.hh"
@@ -29,6 +31,10 @@
#include "GPU_texture.hh"
#include "GPU_viewport.hh"
#ifdef __EMSCRIPTEN__
# include "../webgl/webgl_texture.hh"
#endif
#include "DRW_engine.hh"
#include "MEM_guardedalloc.h"
@@ -94,6 +100,24 @@ enum {
GPU_VIEWPORT_STEREO = (1 << 1),
};
#ifdef __EMSCRIPTEN__
static bool gpu_viewport_has_live_textures(const GPUViewport *viewport)
{
if (!gpu::webgl_texture_has_live_storage(viewport->depth_tx)) {
return false;
}
const int views = (viewport->flag & GPU_VIEWPORT_STEREO) ? 2 : 1;
for (int view = 0; view < views; view++) {
if (!gpu::webgl_texture_has_live_storage(viewport->color_render_tx[view]) ||
!gpu::webgl_texture_has_live_storage(viewport->color_overlay_tx[view]))
{
return false;
}
}
return true;
}
#endif
void GPU_viewport_tag_update(GPUViewport *viewport)
{
viewport->flag |= DO_UPDATE;
@@ -103,6 +127,11 @@ bool GPU_viewport_do_update(GPUViewport *viewport)
{
bool ret = (viewport->flag & DO_UPDATE);
viewport->flag &= ~DO_UPDATE;
#ifdef __EMSCRIPTEN__
/* A restored canvas can have the same dimensions and no pending scene edits.
* Ask WM to draw before it composites retained, but lost, region textures. */
ret |= !gpu_viewport_has_live_textures(viewport);
#endif
return ret;
}
@@ -146,6 +175,12 @@ static void gpu_viewport_textures_create(GPUViewport *viewport)
viewport->color_overlay_tx[0] = GPU_texture_create_2d(
"dtxl_color_overlay", UNPACK2(size), 1, gpu::TextureFormat::SRGBA_8_8_8_8, usage, nullptr);
#ifdef __EMSCRIPTEN__
if (!viewport->color_render_tx[0] || !viewport->color_overlay_tx[0]) {
throw std::runtime_error("WebGL viewport color attachment allocation failed");
}
#endif
GPU_texture_clear(viewport->color_render_tx[0], GPU_DATA_FLOAT, empty_pixel);
GPU_texture_clear(viewport->color_overlay_tx[0], GPU_DATA_FLOAT, empty_pixel);
}
@@ -164,6 +199,12 @@ static void gpu_viewport_textures_create(GPUViewport *viewport)
usage,
nullptr);
#ifdef __EMSCRIPTEN__
if (!viewport->color_render_tx[1] || !viewport->color_overlay_tx[1]) {
throw std::runtime_error("WebGL stereo viewport attachment allocation failed");
}
#endif
GPU_texture_clear(viewport->color_render_tx[1], GPU_DATA_FLOAT, empty_pixel);
GPU_texture_clear(viewport->color_overlay_tx[1], GPU_DATA_FLOAT, empty_pixel);
}
@@ -179,12 +220,23 @@ static void gpu_viewport_textures_create(GPUViewport *viewport)
usage | GPU_TEXTURE_USAGE_HOST_READ |
GPU_TEXTURE_USAGE_FORMAT_VIEW,
nullptr);
#ifdef __EMSCRIPTEN__
if (!viewport->depth_tx) {
throw std::runtime_error("WebGL viewport depth attachment allocation failed");
}
#endif
const float depth_clear = 0.0f;
GPU_texture_clear(viewport->depth_tx, GPU_DATA_FLOAT, &depth_clear);
}
if (!viewport->depth_tx || !viewport->color_render_tx[0] || !viewport->color_overlay_tx[0]) {
#ifdef __EMSCRIPTEN__
/* The caller owns this viewport. Freeing it in a void allocation helper
* leaves offscreen render callers with a dangling pointer. */
throw std::runtime_error("WebGL viewport attachment allocation failed");
#else
GPU_viewport_free(viewport);
#endif
}
}
@@ -211,11 +263,33 @@ void GPU_viewport_bind(GPUViewport *viewport, int view, const rcti *rect)
DRW_gpu_context_enable();
#ifdef __EMSCRIPTEN__
try {
/* GP placement queries bind through WM before the next regular redraw.
* Restore the whole region target here, before DRW borrows its depth owner.
* Keep DRWData and the original scene/cache producers; only pixels were lost. */
if (viewport->size != rect_size || !gpu_viewport_has_live_textures(viewport)) {
copy_v2_v2_int(viewport->size, rect_size);
gpu_viewport_textures_free(viewport);
gpu_viewport_textures_create(viewport);
GPU_viewport_tag_update(viewport);
}
}
catch (...) {
/* No partial stereo/color/depth set may survive an allocation or clear
* failure. The next bind retries even though size already matches. */
gpu_viewport_textures_free(viewport);
GPU_viewport_tag_update(viewport);
DRW_gpu_context_disable();
throw;
}
#else
if (viewport->size != rect_size) {
copy_v2_v2_int(viewport->size, rect_size);
gpu_viewport_textures_free(viewport);
gpu_viewport_textures_create(viewport);
}
#endif
viewport->active_view = view;
}
@@ -239,6 +313,7 @@ void GPU_viewport_bind_from_offscreen(GPUViewport *viewport, GPUOffScreen *ofs,
/* This is the only texture we can share. */
viewport->depth_tx = depth;
if (depth) { GPU_texture_ref(depth); }
gpu_viewport_textures_create(viewport);
}
@@ -291,6 +366,11 @@ void GPU_viewport_stereo_composite(GPUViewport *viewport, Stereo3dFormat *stereo
* done from a single viewport. See `wm_stereo.cc`. */
return;
}
#ifdef __EMSCRIPTEN__
if (!gpu_viewport_has_live_textures(viewport)) {
throw std::runtime_error("Browser region requires redraw before stereo composition");
}
#endif
/* The composite framebuffer object needs to be created in the window context. */
GPU_framebuffer_ensure_config(
&viewport->stereo_comp_fb,
@@ -461,7 +541,22 @@ static void gpu_viewport_draw_colormanaged(GPUViewport *viewport,
viewport->dither,
false,
do_overlay_merge);
#ifdef __EMSCRIPTEN__
/* A requested native display transform must not become a successful
* untransformed preview when OCIO shader/resource construction fails. */
if (!use_ocio) {
throw std::runtime_error("Native viewport composition: OCIO display transform is unavailable");
}
#endif
}
auto release_composition = [&](GPUViewport *) {
/* Run all cleanup even if context loss prevents one unbind. */
try { GPU_texture_unbind(color); } catch (...) {}
try { GPU_texture_unbind(color_overlay); } catch (...) {}
try { if (use_ocio) { IMB_colormanagement_finish_glsl_draw(); } } catch (...) {}
};
std::unique_ptr<GPUViewport, decltype(release_composition)> composition_scope(
viewport, release_composition);
gpu::Batch *batch = gpu_viewport_batch_get(viewport, rect_pos, rect_uv);
if (use_ocio) {
@@ -477,12 +572,6 @@ static void gpu_viewport_draw_colormanaged(GPUViewport *viewport,
GPU_texture_bind(color, 0);
GPU_texture_bind(color_overlay, 1);
GPU_batch_draw(batch);
GPU_texture_unbind(color);
GPU_texture_unbind(color_overlay);
if (use_ocio) {
IMB_colormanagement_finish_glsl_draw();
}
}
void GPU_viewport_draw_to_screen_ex(GPUViewport *viewport,
@@ -547,6 +636,8 @@ void GPU_viewport_unbind_from_offscreen(GPUViewport *viewport,
bool do_overlay_merge)
{
const int view = 0;
auto release_depth = [](GPUViewport *view) { GPU_TEXTURE_FREE_SAFE(view->depth_tx); };
std::unique_ptr<GPUViewport, decltype(release_depth)> depth_scope(viewport, release_depth);
if (viewport->color_render_tx[view] == nullptr) {
return;
@@ -570,8 +661,8 @@ void GPU_viewport_unbind_from_offscreen(GPUViewport *viewport,
gpu_viewport_draw_colormanaged(
viewport, view, &pos_rect, &uv_rect, display_colorspace, do_overlay_merge);
/* This one is from the offscreen. Don't free it with the viewport. */
viewport->depth_tx = nullptr;
/* Release the reference acquired by bind_from_offscreen on success, early
* return or a backend exception; the offscreen keeps its original reference. */
}
void GPU_viewport_unbind(GPUViewport * /*viewport*/)

View File

@@ -94,7 +94,8 @@ void SourceProcessor::lower_enums(Parser &parser)
if (class_tok.is_valid()) {
name = enum_name_str + "::" + name;
}
string decl = "constant static constexpr " + type_str + " " + name + " " + value + ";\n";
string decl = "constant static constexpr " + type_str + " " + name + " = " + type_str +
"(" + value.substr(1) + ");\n";
parser.insert_line_number(enum_tok.prev(), name_tok.line_number());
parser.insert_after(enum_tok.prev(), decl);

View File

@@ -38,7 +38,7 @@ struct Scope {
Scope(const ParserBase &parser, int64_t index) : parser_(&parser), index_(index)
{
if (index < 0 || index >= parser.scope_types.size()) {
index = parser.scope_types.size();
index_ = parser.scope_types.size();
return;
}
#ifndef NDEBUG

View File

@@ -29,12 +29,23 @@ uint gpu_index_load(uint element_index)
return element_index;
}
#ifdef GPU_WEBGL
uint raw_index = gpu_webgl_load_gpu_index_buf(gpu_index_16bit ? element_index >> 1u :
element_index);
#else
uint raw_index = gpu_index_buf[gpu_index_16bit ? element_index >> 1u : element_index];
#endif
if (gpu_index_16bit) {
raw_index = ((element_index & 1u) == 0u) ? (raw_index & 0xFFFFu) : (raw_index >> 16u);
}
#ifdef GPU_WEBGL
/* Preserve fixed restart before adding the compressed buffer's base index. */
if (raw_index == (gpu_index_16bit ? 0xFFFFu : 0xFFFFFFFFu)) {
return 0xFFFFFFFFu;
}
#endif
return raw_index + uint(gpu_index_base_index);
}

View File

@@ -69,14 +69,14 @@ uint rgb9e5_encode(float3 color)
{
rgb9e5_t result = rgb9e5_from_float3(color);
result.exp_shared <<= RGB9E5_MANTISSA_BITS * 3;
result.mantissa <<= RGB9E5_MANTISSA_BITS * uint3(0, 1, 2);
result.mantissa <<= uint(RGB9E5_MANTISSA_BITS) * uint3(0, 1, 2);
return result.mantissa.r | result.mantissa.g | result.mantissa.b | result.exp_shared;
}
float3 rgb9e5_decode(uint data)
{
int exp_shared = int(data >> (RGB9E5_MANTISSA_BITS * 3));
uint3 mantissa = (uint3(data) >> (RGB9E5_MANTISSA_BITS * uint3(0, 1, 2))) &
uint3 mantissa = (uint3(data) >> (uint(RGB9E5_MANTISSA_BITS) * uint3(0, 1, 2))) &
uint(MAX_RGB9E5_MANTISSA);
return float3(mantissa) * rgb9e5_exponent_factor(exp_shared);
}

View File

@@ -6,15 +6,20 @@
#include "gpu_shader_compat.hh"
#ifdef GPU_WEBGL
/* WebGL stores the single-mip tile map layers as rows. Integer fetches are unchanged. */
bool tiled_image_lookup(float3 &co, sampler2DArray ima, sampler2D map)
#else
bool tiled_image_lookup(float3 &co, sampler2DArray ima, sampler1DArray map)
#endif
{
float2 tile_pos = floor(co.xy);
if (tile_pos.x < 0 || tile_pos.y < 0 || tile_pos.x >= 10) {
if (tile_pos.x < 0.0f || tile_pos.y < 0.0f || tile_pos.x >= 10.0f) {
return false;
}
float tile = 10 * tile_pos.y + tile_pos.x;
if (tile >= textureSize(map, 0).x) {
float tile = 10.0f * tile_pos.y + tile_pos.x;
if (tile >= float(textureSize(map, 0).x)) {
return false;
}
/* Fetch tile information. */

View File

@@ -105,9 +105,9 @@ void main()
case SOCK_DISPLAY_SHAPE_VOLUME_GRID: {
constexpr float rect_side_length = 0.25f;
const float2 oversize = float2(0.0f, square_radius * 1.4) / 2.5f;
const float2 rect_corner = max(float2(rect_side_length), extrusion / 2.0f + oversize) +
float2 rect_corner = max(float2(rect_side_length), extrusion / 2.0f + oversize) +
finalOutlineThickness / 4.0f;
const float2 mirrored_uv = abs(abs(uv) - rect_corner);
float2 mirrored_uv = abs(abs(uv) - rect_corner);
distance_squared = square_sdf(mirrored_uv, rect_corner + finalOutlineThickness / 2.0f);
alpha_threshold = corner_rounding;
break;
@@ -115,9 +115,9 @@ void main()
case SOCK_DISPLAY_SHAPE_LIST: {
constexpr float2 rect_side_length = float2(0.5f, 0.25f);
const float2 oversize = float2(0.0f, square_radius * 1.4) / 2.5f;
const float2 rect_corner = max(rect_side_length, extrusion / 2.0f + oversize) +
float2 rect_corner = max(rect_side_length, extrusion / 2.0f + oversize) +
finalOutlineThickness / 4.0f;
const float2 mirrored_uv = float2(
float2 mirrored_uv = float2(
abs(uv.x), abs(abs(abs(uv.y) - rect_corner.y / 1.5f) - rect_corner.y / 1.5f));
distance_squared = square_sdf(
mirrored_uv, (rect_corner + finalOutlineThickness / 2.0f) / float2(1.0f, 1.5f));

View File

@@ -284,15 +284,16 @@ struct Resources {
InnerType v0, v1, v2, h0, h1, h2, out_pixel;
/* Reduce vertically up to 3 times (depending on kernel horizontal size) */
switch (kernel_size.x) {
case 3:
/* Keep the same sample order without switch fall-through for WGSL translation. */
{
if (kernel_size.x == 3) {
switch (kernel_size.y) {
case 3:
v2 = load_sample(src_coord + int2(2, 2), load_from_shared);
ATTR_FALLTHROUGH;
v1 = load_sample(src_coord + int2(2, 1), load_from_shared); v0 = load_sample(src_coord + int2(2, 0), load_from_shared); break;
case 2:
v1 = load_sample(src_coord + int2(2, 1), load_from_shared);
ATTR_FALLTHROUGH;
v0 = load_sample(src_coord + int2(2, 0), load_from_shared); break;
case 1:
v0 = load_sample(src_coord + int2(2, 0), load_from_shared);
break;
@@ -308,15 +309,14 @@ struct Resources {
h2 = v0;
break;
}
ATTR_FALLTHROUGH;
case 2:
} if (kernel_size.x == 2 || kernel_size.x == 3) {
switch (kernel_size.y) {
case 3:
v2 = load_sample(src_coord + int2(1, 2), load_from_shared);
ATTR_FALLTHROUGH;
v1 = load_sample(src_coord + int2(1, 1), load_from_shared); v0 = load_sample(src_coord + int2(1, 0), load_from_shared); break;
case 2:
v1 = load_sample(src_coord + int2(1, 1), load_from_shared);
ATTR_FALLTHROUGH;
v0 = load_sample(src_coord + int2(1, 0), load_from_shared); break;
case 1:
v0 = load_sample(src_coord + int2(1, 0), load_from_shared);
break;
@@ -332,15 +332,14 @@ struct Resources {
h1 = v0;
break;
}
ATTR_FALLTHROUGH;
case 1:
} if (kernel_size.x >= 1 && kernel_size.x <= 3) {
switch (kernel_size.y) {
case 3:
v2 = load_sample(src_coord + int2(0, 2), load_from_shared);
ATTR_FALLTHROUGH;
v1 = load_sample(src_coord + int2(0, 1), load_from_shared); v0 = load_sample(src_coord + int2(0, 0), load_from_shared); break;
case 2:
v1 = load_sample(src_coord + int2(0, 1), load_from_shared);
ATTR_FALLTHROUGH;
v0 = load_sample(src_coord + int2(0, 0), load_from_shared); break;
case 1:
v0 = load_sample(src_coord + int2(0, 0), load_from_shared);
break;
@@ -356,6 +355,7 @@ struct Resources {
h0 = v0;
break;
}
}
}
/* Reduce up to 3 samples horizontally. */
@@ -527,7 +527,10 @@ void update_mipmaps([[global_invocation_id]] const uint3 global_id,
[[local_invocation_id]] const uint3 local_index,
[[resource_table]] Resources<format, SharedStorage, InnerType> &srt)
{
if (srt.num_levels == 1u) {
const bool two_levels = srt.num_levels != 1u;
int2 tile_index = int2(0);
bool use_bounds_check = false;
if (!two_levels) {
int2 kernel_size = kernel_size_from_input_size(srt.level_size(INPUT_LEVEL));
int2 dst_image_size = srt.level_size(INPUT_LEVEL + 1);
int2 dst_coord = int2(int(global_id.x) % dst_image_size.x,
@@ -547,32 +550,32 @@ void update_mipmaps([[global_invocation_id]] const uint3 global_id,
int2 tile_count;
tile_count.x = int(uint(level2_size.x + 7) / 8u);
tile_count.y = int(uint(level2_size.y + 7) / 8u);
int2 tile_index = int2(group_id.x % uint(tile_count.x), group_id.x / uint(tile_count.x));
tile_index = int2(group_id.x % uint(tile_count.x), group_id.x / uint(tile_count.x));
/* Determine if bounds checking is needed; this is only the case
* for tiles at the right or bottom fringe that might be cut off
* by the image border. Note that later, I use if statements rather
* than passing use_bounds_check directly to convince the compiler
* to inline everything. */
bool use_bounds_check = tile_index.x >= tile_count.x - 1 || tile_index.y >= tile_count.y - 1;
use_bounds_check = tile_index.x >= tile_count.x - 1 || tile_index.y >= tile_count.y - 1;
if (use_bounds_check) {
/* Compute the tile in level inputLevel_ + 1 that's needed to
* compute the above 8x8 tile. */
srt.fill_intermediate_tile(local_index.x, tile_index * 2 * int2(8, 8), true);
barrier();
/* Compute the inputLevel_ + 2 tile of size 8x8, loading
* inputs from shared memory. */
srt.fill_last_tile(local_index.x, tile_index * int2(8, 8), true);
}
else {
/* Same but without bounds checking. */
srt.fill_intermediate_tile(local_index.x, tile_index * 2 * int2(8, 8), false);
barrier();
srt.fill_last_tile(local_index.x, tile_index * int2(8, 8), false);
}
}
/* Every lane reaches the barrier before consuming intermediate shared pixels. */
barrier();
if (two_levels) {
if (use_bounds_check) { srt.fill_last_tile(local_index.x, tile_index * int2(8, 8), true); }
else { srt.fill_last_tile(local_index.x, tile_index * int2(8, 8), false); }
}
}
template struct Shared<float>;

View File

@@ -296,7 +296,9 @@ struct Resources {
bool is_tria = (vert_id > 3);
float2 pos;
VertOut vert_out = (is_tria) ? widget.do_tria(vert_id, pos) : widget.do_widget(vert_id, pos);
VertOut vert_out;
if (is_tria) { vert_out = widget.do_tria(vert_id, pos); }
else { vert_out = widget.do_widget(vert_id, pos); }
/* WORKAROUND: Quirk of current BSL implementation.
* Current implementation doesn't allow to assign the output struct at once. */

View File

@@ -16,6 +16,26 @@ struct VertIn {
float4 final_color;
};
float polyline_position_load(uint address)
{
#ifdef GPU_WEBGL
return uintBitsToFloat(gpu_webgl_load_pos(address));
#else
return pos[address];
#endif
}
#ifndef UNIFORM
float polyline_color_load(uint address)
{
# ifdef GPU_WEBGL
return uintBitsToFloat(gpu_webgl_load_color(address));
# else
return color[address];
# endif
}
#endif
VertIn input_assembly(uint in_vertex_id)
{
uint v_i = gpu_index_load(in_vertex_id);
@@ -24,12 +44,12 @@ VertIn input_assembly(uint in_vertex_id)
VertIn vert_in;
vert_in.ls_P = float3(0.0f, 0.0f, 0.0f);
/* Need to support 1, 2 and 3 dimensional input (sigh). */
vert_in.ls_P.x = pos[gpu_attr_load_index(v_i, gpu_attr_0) + 0 + ofs];
vert_in.ls_P.x = polyline_position_load(gpu_attr_load_index(v_i, gpu_attr_0) + 0u + ofs);
if (gpu_attr_0_len >= 2) {
vert_in.ls_P.y = pos[gpu_attr_load_index(v_i, gpu_attr_0) + 1 + ofs];
vert_in.ls_P.y = polyline_position_load(gpu_attr_load_index(v_i, gpu_attr_0) + 1u + ofs);
}
if (gpu_attr_0_len >= 3) {
vert_in.ls_P.z = pos[gpu_attr_load_index(v_i, gpu_attr_0) + 2 + ofs];
vert_in.ls_P.z = polyline_position_load(gpu_attr_load_index(v_i, gpu_attr_0) + 2u + ofs);
}
if (gpu_attr_0_fetch_int) {
@@ -38,19 +58,26 @@ VertIn input_assembly(uint in_vertex_id)
#ifndef UNIFORM
vert_in.final_color = float4(0.0f, 0.0f, 0.0f, 1.0f);
/* Need to support 1, 2, 3 and 4 dimensional input (sigh). */
vert_in.final_color.x = color[gpu_attr_load_index(v_i, gpu_attr_1) + 0 + ofs];
if (gpu_attr_1_fetch_unorm8) {
# ifdef GPU_WEBGL
/* Decode packed bytes before float conversion, including bit patterns that encode NaNs. */
uint packed_color = gpu_webgl_load_color(gpu_attr_load_index(v_i, gpu_attr_1) + ofs);
vert_in.final_color = float4(gpu_attr_decode_uchar4_to_uint4(packed_color)) / 255.0f;
# else
vert_in.final_color.x = color[gpu_attr_load_index(v_i, gpu_attr_1) + ofs];
vert_in.final_color = unpackUnorm4x8(floatBitsToUint(vert_in.final_color.x));
# endif
}
else {
vert_in.final_color.x = polyline_color_load(gpu_attr_load_index(v_i, gpu_attr_1) + ofs);
if (gpu_attr_1_len >= 2) {
vert_in.final_color.y = color[gpu_attr_load_index(v_i, gpu_attr_1) + 1 + ofs];
vert_in.final_color.y = polyline_color_load(gpu_attr_load_index(v_i, gpu_attr_1) + 1u + ofs);
}
if (gpu_attr_1_len >= 3) {
vert_in.final_color.z = color[gpu_attr_load_index(v_i, gpu_attr_1) + 2 + ofs];
vert_in.final_color.z = polyline_color_load(gpu_attr_load_index(v_i, gpu_attr_1) + 2u + ofs);
}
if (gpu_attr_1_len >= 4) {
vert_in.final_color.w = color[gpu_attr_load_index(v_i, gpu_attr_1) + 3 + ofs];
vert_in.final_color.w = polyline_color_load(gpu_attr_load_index(v_i, gpu_attr_1) + 3u + ofs);
}
}
#endif
@@ -134,8 +161,15 @@ void do_vertex(const uint i,
geom_out.final_color = color;
#elif defined(FLAT)
# ifdef GPU_WEBGL
/* Triangle provoking-vertex rotation cannot choose the input line's color:
* all six expanded vertices carry the same flat value. Keep endpoint order
* (and thus clipping/winding) intact and select the native source explicitly. */
geom_out.final_color = geom_in[gpu_webgl_polyline_first_vertex ? 0 : 1].final_color;
# else
/* WATCH: Assuming last provoking vertex. */
geom_out.final_color = geom_in[1].final_color;
# endif
#elif defined(SMOOTH)
geom_out.final_color = geom_in[i].final_color;
@@ -201,10 +235,26 @@ void main()
output_invocation_count;
/* Used to wrap around for the line loop case. */
uint input_total_vertex_count = uint(gpu_vert_stride_count_offset.y);
uint index_start = uint(gpu_polyline_index_start);
uint first_vertex = index_start + in_primitive_first_vertex;
uint second_vertex = index_start + (in_primitive_first_vertex + 1u) % input_total_vertex_count;
#ifdef GPU_WEBGL
/* Expanded draws must discard restart segments before fetching their vertex attributes. */
if (gpu_index_load(first_vertex) == 0xFFFFFFFFu ||
gpu_index_load(second_vertex) == 0xFFFFFFFFu)
{
gl_Position = float4(2.0f, 2.0f, 2.0f, 1.0f);
final_color = float4(0.0f);
smoothline = 0.0f;
clip = 0.0f;
return;
}
#endif
VertIn vert_in[2];
vert_in[0] = input_assembly(in_primitive_first_vertex + 0u);
vert_in[1] = input_assembly((in_primitive_first_vertex + 1u) % input_total_vertex_count);
vert_in[0] = input_assembly(first_vertex);
vert_in[1] = input_assembly(second_vertex);
VertOut vert_out[2];
vert_out[0] = vertex_main(vert_in[0]);

View File

@@ -10,7 +10,7 @@ void main()
{
float phase = mod((gl_FragCoord.x + gl_FragCoord.y), float(size1 + size2));
if (phase < size1) {
if (phase < float(size1)) {
fragColor = color1;
}
else {

View File

@@ -46,13 +46,13 @@ void main()
outline_dist = max(outline_dist, absPos.x - radii[2]);
}
float alpha = 1 - smoothstep(thresholds[0], thresholds[1], abs(outline_dist));
float alpha = 1.0f - smoothstep(thresholds[0], thresholds[1], abs(outline_dist));
/* Inside the outline. */
if (outline_dist < 0) {
if (outline_dist < 0.0f) {
/* Middle dot */
if (test(GPU_KEYFRAME_SHAPE_INNER_DOT)) {
alpha = max(alpha, 1 - smoothstep(thresholds[2], thresholds[3], length(absPos)));
alpha = max(alpha, 1.0f - smoothstep(thresholds[2], thresholds[3], length(absPos)));
}
/* Up and down arrow-like shading. */

View File

@@ -26,11 +26,11 @@ void main()
gl_Position = ModelViewProjectionMatrix * float4(pos, 0.0f, 1.0f);
/* Align to pixel grid if the viewport size is known. */
if (ViewportSize.x > 0) {
if (ViewportSize.x > 0.0f) {
float2 scale = ViewportSize * 0.5f;
float2 px_pos = (gl_Position.xy + 1) * scale;
float2 px_pos = (gl_Position.xy + 1.0f) * scale;
float2 adj_pos = round(px_pos - 0.5f) + 0.5f;
gl_Position.xy = adj_pos / scale - 1;
gl_Position.xy = adj_pos / scale - 1.0f;
}
/* Pass through parameters. */
@@ -45,7 +45,7 @@ void main()
}
/* Size-dependent line thickness. */
float half_width = (0.06f + (size - 10) * 0.04f);
float half_width = (0.06f + (size - 10.0f) * 0.04f);
float line_width = half_width + line_falloff;
/* Outline thresholds. */
@@ -57,7 +57,7 @@ void main()
/* Extend the primitive size by half line width on either side; odd for symmetry. */
float ext_radius = round(0.5f * size) + thresholds.x;
gl_PointSize = ceil(ext_radius + thresholds.y) * 2 + 1;
gl_PointSize = ceil(ext_radius + thresholds.y) * 2.0f + 1.0f;
/* Diamond radius. */
radii[0] = ext_radius * diagonal_scale;

View File

@@ -83,7 +83,7 @@ void main()
uint shadow_type = glyph_flags & 0xFu;
/* Colored glyphs: do not do filtering or blurring. */
if (num_channels == 4) {
if (num_channels == 4u) {
fragColor.rgba = sample_glyph_rgba(uv_base).rgba;
fragColor.a *= color_flat.a;
return;
@@ -93,7 +93,7 @@ void main()
fragColor.rgb = color_flat.rgb;
if (shadow_type == 0) {
if (shadow_type == 0u) {
/* No blurring: just a bilinear sample. */
fragColor.a = sample_glyph_bilinear(bilin_f, uv_base);
}
@@ -106,7 +106,7 @@ void main()
int2 texel = int2(floor(uv_base)) - 1;
int frag_offset = glyph_offset + texel.y * glyph_dim.x + texel.x;
if (shadow_type == 6) {
if (shadow_type == 6u) {
/* 3x3 outline by dilation */
float maxval = 0.0f;
@@ -131,7 +131,7 @@ void main()
}
fragColor.a = maxval;
}
else if (shadow_type <= 4) {
else if (shadow_type <= 4u) {
/* 3x3 blur */
/* clang-format off */

View File

@@ -17,7 +17,7 @@ void main()
/* Depending on shadow outline / blur level, we might need to expand the quad. */
uint shadow_type = glyph_flags & 0xFu;
int interp_size = shadow_type > 4 ? 2 : (shadow_type > 0 ? 1 : 0);
int interp_size = shadow_type > 4u ? 2 : (shadow_type > 0u ? 1 : 0);
/* Quad expansion using instanced rendering. */
float x = float(gl_VertexID % 2);

View File

@@ -37,6 +37,7 @@ PUSH_CONSTANT(bool, lineSmooth)
STORAGE_BUF_FREQ(GPU_SSBO_POLYLINE_POS_BUF_SLOT, read, float, pos[], GEOMETRY)
PUSH_CONSTANT(int2, gpu_attr_0)
PUSH_CONSTANT(int3, gpu_vert_stride_count_offset)
PUSH_CONSTANT(int, gpu_polyline_index_start)
PUSH_CONSTANT(int, gpu_attr_0_len)
PUSH_CONSTANT(bool, gpu_attr_0_fetch_int)
PUSH_CONSTANT(bool, gpu_attr_1_fetch_unorm8)

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,90 @@
/* SPDX-FileCopyrightText: 2026 Blender Authors
*
* SPDX-License-Identifier: GPL-2.0-or-later */
#pragma once
#include <functional>
#include "gpu_backend.hh"
namespace blender::gpu {
/* The caller keeps the framebuffer and its attachments alive until restoration. */
std::function<void()> webgl_framebuffer_state_capture(FrameBuffer *framebuffer);
/* Replay a native viewport-index draw against the framebuffer's original array. */
void webgl_framebuffer_viewport_draw(const std::function<void(int)> &submit);
/* Native bindings only: restoring a scope never rolls back buffer/texture contents. */
std::function<void()> webgl_resource_state_capture();
/* CPU selection caches still belong to the browser context that rendered them. */
std::function<bool()> webgl_select_cache_validity_capture();
/* Retire a cached selection owner when a native gesture is cancelled. */
void webgl_select_cache_invalidate();
void webgl_select_check_interrupt();
/* Keep ordinary UBO bindings below this slot. WebGL2 has no SSBO binding namespace. */
constexpr int WEBGL_GLYPH_UBO_SLOT = 15;
/* Workbench's read-only material SSBO uses four R32UI texels per native material.
* Keep this separate from its image/matcap samplers and geometry fetch bindings. */
constexpr int WEBGL_WORKBENCH_MATERIAL_TEXTURE_SLOT = 15;
constexpr int WEBGL_OBJECT_MATRIX_TEXTURE_SLOT = 14;
constexpr int WEBGL_OBJECT_INFO_TEXTURE_SLOT = 13;
constexpr int WEBGL_RESOURCE_ID_TEXTURE_SLOT = 12;
constexpr int WEBGL_OBJECT_ATTRIBUTE_TEXTURE_SLOT = 11;
constexpr int WEBGL_OVERLAY_INSTANCE_TEXTURE_SLOT = 10;
constexpr int WEBGL_SELECT_INPUT_TEXTURE_SLOT = 9;
/* GP geometry uses samplers 0..5 and Manager slots 11..14. Its original
* 255 * 112 byte material UBO exceeds WebGL2's guaranteed 16 KiB block. */
constexpr int WEBGL_GP_MATERIAL_TEXTURE_SLOT = 8;
constexpr int WEBGL_GP_MATERIAL_UBO_SLOT = 4;
constexpr int WEBGL_SHADOW_VIEW_TEXTURE_SLOT = 7;
constexpr int WEBGL_SHADOW_VIEW_STORAGE_SLOT = 5;
constexpr size_t WEBGL_SHADOW_VIEW_BYTES = 64 * 48;
/* eevee_defines.hh: one uint page address for each of 32*32 tiles in 64 views.
* Keep the fragment map separate from the vertex render-view texture. */
constexpr int WEBGL_SHADOW_MAP_TEXTURE_SLOT = 6;
constexpr int WEBGL_SHADOW_MAP_STORAGE_SLOT = 3;
constexpr size_t WEBGL_SHADOW_MAP_BYTES = 64 * 32 * 32 * sizeof(uint32_t);
constexpr size_t WEBGL_GP_MATERIAL_BYTES = 255 * 112;
/* Original select_defines.hh bindings (separate UBO/SSBO namespaces). */
constexpr int WEBGL_SELECT_INFO_SLOT = 4;
constexpr int WEBGL_SELECT_INPUT_SLOT = 5;
constexpr int WEBGL_SELECT_OUTPUT_SLOT = 6;
/* Native draw_defines.hh storage bindings; these are not WebGL texture units. */
constexpr int WEBGL_OBJECT_MATRIX_STORAGE_SLOT = 10;
constexpr int WEBGL_OBJECT_INFO_STORAGE_SLOT = 9;
constexpr int WEBGL_RESOURCE_ID_STORAGE_SLOT = 11;
constexpr int WEBGL_OBJECT_ATTRIBUTE_STORAGE_SLOT = 8;
/** WebGL2 context and window framebuffer backend. Shader/resource support is still incomplete. */
class WebGLBackend : public GPUBackend {
public:
WebGLBackend();
~WebGLBackend() override;
static bool is_supported();
void init_resources() override;
void delete_resources() override;
Context *context_alloc(GHOST_IWindow *window, GHOST_IContext *context) override;
FrameBuffer *framebuffer_alloc(const char *name) override;
TexturePool *texturepool_alloc() override;
Fence *fence_alloc() override;
Batch *batch_alloc() override;
IndexBuf *indexbuf_alloc() override;
PixelBuffer *pixelbuf_alloc(size_t size) override;
QueryPool *querypool_alloc() override;
Shader *shader_alloc(const char *name) override;
Texture *texture_alloc(const char *name) override;
UniformBuf *uniformbuf_alloc(size_t size, const char *name) override;
StorageBuf *storagebuf_alloc(size_t size, GPUUsageType usage, const char *name) override;
VertBuf *vertbuf_alloc() override;
void compute_dispatch(int x, int y, int z) override;
void compute_dispatch_indirect(StorageBuf *buffer) override;
void shader_cache_dir_clear_old() override;
void render_begin() override;
void render_end() override;
void render_step(bool force_resource_release) override;
};
} // namespace blender::gpu

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,24 @@
/* SPDX-FileCopyrightText: 2026 Blender Authors
*
* SPDX-License-Identifier: GPL-2.0-or-later */
#pragma once
#include <cstddef>
#include <cstdint>
#include <vector>
namespace blender::gpu {
class Batch;
class IndexBuf;
class VertBuf;
class Immediate;
class StorageBuf;
Batch *webgl_batch_alloc();
IndexBuf *webgl_indexbuf_alloc();
VertBuf *webgl_vertbuf_alloc();
Immediate *webgl_immediate_alloc();
/* Read only synchronized native command storage, with bounds checked before allocation. */
std::vector<uint32_t> webgl_indirect_snapshot(StorageBuf *buffer, size_t offset, size_t size);
} // namespace blender::gpu

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,138 @@
/* SPDX-FileCopyrightText: 2026 Blender Authors
*
* SPDX-License-Identifier: GPL-2.0-or-later */
#pragma once
#include <cstddef>
#include <cstdint>
#include <functional>
#include <memory>
#include "BLI_math_vector_types.hh"
#include "BLI_span.hh"
#include "GPU_framebuffer.hh"
#include "GPU_state.hh"
#include "GPU_uniform_buffer.hh"
namespace blender::gpu {
class Shader;
class StorageBuf;
class UniformBuf;
class VertBuf;
class IndexBuf;
class Context;
class Texture;
/* A native caller can span several dispatches without publishing a partial
* capture on failure. Recording is explicit: unrelated capture raster/compute
* work is not part of the persistent atlas/lighting transaction. */
class WebGLComputeTransaction {
struct State;
std::unique_ptr<State> state_;
public:
WebGLComputeTransaction();
~WebGLComputeTransaction();
void commit() noexcept;
/* Enlist native caller metadata/owner replacement in the active transaction.
* Register before mutation. The callback must not throw or allocate, and its
* caller-owned references must outlive the synchronous transaction. Captured
* resources remain alive until rollback finishes or the transaction commits. */
static void record_rollback(std::function<void()> restore);
WebGLComputeTransaction(const WebGLComputeTransaction &) = delete;
WebGLComputeTransaction &operator=(const WebGLComputeTransaction &) = delete;
class Recording {
public:
Recording();
~Recording();
Recording(const Recording &) = delete;
Recording &operator=(const Recording &) = delete;
};
};
/* Prepared on the engine thread after readback. Applying a prepared write must
* not allocate, call browser APIs or fail: every owner is committed as one batch. */
struct WebGLComputeCommit {
void *owner;
const void *data;
size_t size;
void (*apply)(void *owner, const void *data, size_t size) noexcept;
void commit() const noexcept { apply(owner, data, size); }
};
WebGLComputeCommit webgl_storagebuf_compute_prepare(StorageBuf *buffer,
const void *data,
size_t size);
WebGLComputeCommit webgl_vertbuf_compute_prepare(VertBuf *buffer, const void *data, size_t size);
void webgl_vertbuf_compute_barrier(VertBuf *buffer);
WebGLComputeCommit webgl_indexbuf_compute_prepare(IndexBuf *buffer, const void *data, size_t size);
void webgl_indexbuf_compute_barrier(IndexBuf *buffer);
WebGLComputeCommit webgl_uniformbuf_compute_prepare(UniformBuf *buffer,
const void *data,
size_t size);
void webgl_uniformbuf_compute_barrier(UniformBuf *buffer);
/* Materialize a known physical raster UBO before its native caller publishes
* display state. Unlike a generic barrier, this also creates the first cache. */
void webgl_uniformbuf_publish_raster(UniformBuf *buffer);
/* Copy committed owner bytes, including deferred CPU initialization, without a GL readback. */
void webgl_uniformbuf_read(UniformBuf *buffer, void *data, size_t size);
/* Native buffers own broker allocation lifetimes. Each dispatch synchronizes host snapshots. */
bool webgl_compute_active();
std::function<void()> webgl_shader_state_capture();
/* Physical browser bindings differ from native CreateInfo slots (GP material
* UBOs and draw SSBOs use textures, while glyph SSBOs use a UBO). */
struct WebGLRasterResourceUsage {
uint64_t textures = 0;
uint64_t owner_textures = 0;
uint32_t uniform_buffers = 0;
};
WebGLRasterResourceUsage webgl_raster_resource_usage();
void webgl_raster_clear_storage_slot(int slot);
/* The bound raster CreateInfo, not an allocation name/size, selects the read-only view. */
struct WebGLRasterStorageBinding {
int texture_slot = -1;
size_t record_size = 0;
bool selection_output = false;
bool shadow_tag_output = false;
};
WebGLRasterStorageBinding webgl_shader_storage_binding(int slot);
struct WebGLRasterUniformBinding {
int texture_slot = -1;
size_t byte_size = 0;
};
WebGLRasterUniformBinding webgl_shader_uniform_binding(int slot);
void webgl_compute_bind_image(int slot, Texture *texture);
void webgl_compute_unbind_image(Texture *texture);
void webgl_compute_bind_uniform(int slot, const void *owner, const void *data, size_t size);
void webgl_compute_bind_storage(int slot, StorageBuf *buffer, size_t size);
void webgl_compute_bind_uniform_as_storage(int slot, UniformBuf *buffer, size_t size);
void webgl_compute_bind_vertbuf(int slot, VertBuf *buffer, size_t size);
void webgl_compute_bind_indexbuf(int slot, IndexBuf *buffer, size_t size);
void webgl_compute_unbind_buffer(const void *buffer);
void webgl_compute_forget_buffer(const void *buffer);
void webgl_compute_forget_context(Context *context);
void webgl_compute_dispatch(int x, int y, int z);
void webgl_compute_dispatch_indirect(StorageBuf *buffer);
void webgl_compute_barrier(GPUBarrier barriers);
/* Publish the raster cache of a committed native storage owner without rebinding it. */
void webgl_storagebuf_compute_barrier(StorageBuf *buffer, GPUBarrier barriers);
/* Materialize a native read-only word table without changing shader/slot bindings.
* CPU updates are not compute writes and need not appear in a barrier journal. */
void webgl_storagebuf_publish_raster(StorageBuf *buffer);
/* Scope the native ShadowModule mode; return the previous value for nested draws. */
bool webgl_shadow_atlas_debug_cost_set(bool debug_cost);
bool webgl_shader_shadow_cost(Shader *shader);
Shader *webgl_shader_alloc(const char *name);
void webgl_shader_set_base_instance(Shader *shader, int first);
/* Replay the original selection draw into GPU depth/ID attachments on WebGL2. */
/* Submit through native selection and restore draw-local uniforms even on failure. */
void webgl_shader_draw(Shader *shader, const std::function<void()> &draw, int instance_first = 0,
uint32_t shadow_fragment_bound = 0);
/* Native GP depth, outline and material consumers share bit-encoded vertex data. */
int webgl_shader_encoded_vertex_id_slot(Shader *shader);
/* Original GP resolve and ShadowModule debug fullscreen consumers have two-pass lowering. */
bool webgl_shader_supports_custom_blend(Shader *shader);
void webgl_shader_apply_clip_distances(Shader *shader, int count);
void webgl_shader_apply_texture_swizzles(Shader *shader, Span<const int4> swizzles);
void webgl_shader_apply_subpass_inputs(Shader *shader, Span<const GPUAttachment> attachments);
} // namespace blender::gpu

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,173 @@
/* SPDX-FileCopyrightText: 2026 Blender Authors
*
* SPDX-License-Identifier: GPL-2.0-or-later */
#pragma once
#include <GLES3/gl3.h>
#include <emscripten/html5.h>
#include <memory>
#include <list>
#include <string>
#include <vector>
#include "gpu_texture_private.hh"
#include "webgl_shader.hh"
#include "webgl_texture_state.hh"
namespace blender::gpu {
class WebGLTexture;
/* Resolve the existing native StateManager binding, including its lifetime and sampler. */
WebGLTexture *webgl_compute_sample_binding(int slot, GPUSamplerState &state);
struct WebGLComputeSample {
std::vector<uint32_t> pixels;
std::string descriptor;
};
/* Shared lifetime/revision, without retaining the VBO that owns its cached texture. */
struct WebGLBufferTextureSource {
VertBuf *buffer = nullptr;
uint64_t revision = 0;
};
std::shared_ptr<WebGLBufferTextureSource> webgl_buffer_texture_source(VertBuf *buffer);
/* Texture transfers use isolated attachment views, never a native render-pass bind. */
void webgl_texture_clear_attachment(FrameBuffer *fb, GPUAttachmentType type, double4 value);
void webgl_texture_copy_attachment(FrameBuffer *src,
FrameBuffer *dst,
GPUFrameBufferBits planes,
int width,
int height);
/* Materialize a compute-written atlas before a native raster consumer binds it. */
void webgl_texture_publish_raster(Texture *texture);
/* Preserve shared layers/mips when a native atlas changes its layer count.
* The destination must be initialized separately; new layers are untouched. */
void webgl_texture_copy_array_overlap(Texture *source, Texture *destination, IndexRange levels);
class WebGLTexture : public Texture {
std::shared_ptr<int> lifetime_ = std::make_shared<int>(0);
GLuint id_ = 0;
/* WebGL has no texture-view objects. Writes alias the retained source; sampling
* uses an isolated GPU copy so simultaneous mip views never alter its LOD range. */
WebGLTexture *view_source_ = nullptr;
int view_mip_ = 0, view_layer_ = 0;
bool syncing_view_ = false;
void sync_view();
void copy_compatible_to(WebGLTexture *destination, IndexRange levels);
/* Context-owned transfer program; depth sampling never uses display/color transforms. */
GLuint depth_read_program_ = 0;
GLuint shadow_seed_program_ = 0;
GLuint shadow_count_program_ = 0;
GLuint shadow_count_page_ = 0;
GLuint shadow_pages_[2] = {};
GLuint shadow_framebuffers_[2] = {};
GLuint shadow_depth_ = 0;
GLuint shadow_vao_ = 0;
EMSCRIPTEN_WEBGL_CONTEXT_HANDLE owner_ = 0;
struct Sampler {
GPUSamplerState state;
GLuint id;
};
std::vector<Sampler> samplers_;
/* Bindings retain the mask, not the texture, and observe changes after binding. */
std::shared_ptr<int4> swizzle_ = std::make_shared<int4>(0, 1, 2, 3);
std::shared_ptr<WebGLBufferTextureSource> buffer_source_;
uint64_t buffer_revision_ = 0;
int buffer_width_ = 0, buffer_height_ = 0;
void sync_buffer_texture();
std::vector<uint32_t> compute_pixels_;
bool compute_upload_pending_ = false;
struct ComputeRestore {
int mip, layer, width, height, layers;
eGPUDataFormat format;
std::vector<uint32_t> pixels;
};
std::list<ComputeRestore> compute_restores_;
bool restoring_compute_ = false;
void publish_compute();
public:
explicit WebGLTexture(const char *name) : Texture(name) {}
~WebGLTexture() override;
std::weak_ptr<int> lifetime() const { return lifetime_; }
bool has_live_storage() const;
GLuint id() const;
GLuint attachment_id() const;
int attachment_mip(int mip) const;
int attachment_layer(int layer) const;
int compute_image_layers() const
{
return (type_ == GPU_TEXTURE_2D_ARRAY || type_ == GPU_TEXTURE_3D) ? d_ : 1;
}
eGPUDataFormat compute_image_data_format() const
{
return format_ == TextureFormat::UNORM_8_8_8_8 ? GPU_DATA_UBYTE :
(format_ == TextureFormat::UFLOAT_11_11_10 || format_ == TextureFormat::SFLOAT_32 || format_ == TextureFormat::SFLOAT_32_32_32_32) ? GPU_DATA_FLOAT :
(format_ == TextureFormat::SFLOAT_16 || format_ == TextureFormat::SFLOAT_16_16 || format_ == TextureFormat::SFLOAT_16_16_16_16) ? GPU_DATA_HALF_FLOAT : GPU_DATA_UINT;
}
size_t compute_image_bytes() const;
WebGLComputeSample compute_sample_snapshot(GPUSamplerState state);
WebGLComputeCommit compute_prepare(const void *data, size_t size);
/* Transfer an entire completed atlas without a second atlas-sized allocation. */
WebGLComputeCommit compute_prepare_swap(std::vector<uint32_t> &pixels);
/* Prepare before dispatch; enqueue rollback without allocating or calling GL.
* The parent retains restoration even after the temporary view is destroyed. */
std::function<void()> compute_restore_prepare(const std::vector<uint32_t> &pixels);
GLenum target() const;
/* GPU_texture_create_view(cube_as_array=true) changes the public view target
* while retaining cube-face storage in the source. Framebuffer consumers need
* this bit to select glFramebufferTexture2D rather than a layered attachment. */
bool is_cube_array_view() const
{
return view_source_ && view_source_->type_ == GPU_TEXTURE_CUBE &&
type_ == GPU_TEXTURE_2D_ARRAY;
}
/* During sync_view() the destination is the private sampling copy. Outside
* that transfer, attachments intentionally alias the retained source view. */
bool is_view_transfer() const { return syncing_view_; }
GLuint transfer_attachment_id() const { return syncing_view_ ? id_ : attachment_id(); }
int transfer_attachment_mip(int mip) const
{
return syncing_view_ ? mip : attachment_mip(mip);
}
int transfer_attachment_layer(int layer) const
{
return syncing_view_ ? layer : attachment_layer(layer);
}
std::shared_ptr<const int4> sampling_swizzle() const { return swizzle_; }
GPUSamplerState resolve_sampler(GPUSamplerState state) const
{
return state.type == GPU_SAMPLER_STATE_TYPE_INTERNAL ? sampler_state : state;
}
void bind(GPUSamplerState state, int unit);
void unbind();
void generate_mipmap() override;
void copy_to(Texture *texture, IndexRange mip_levels) override;
void copy_array_overlap_to(WebGLTexture *destination, IndexRange levels);
void clear(double4 value) override;
void swizzle_set(const char mask[4]) override;
void mip_range_set(int min, int max) override;
void read(int mip, eGPUDataFormat format, void *dst) override;
/* Min via radix depth; Add via bounded byte counts accumulated as uints. */
void shadow_atlas_reduce(Span<uint32_t> pages, int texture_unit, int count_unit,
const std::function<void(int, int, int)> &submit);
void read_depth_region(int mip, int layer, const int area[4], float *dst);
/** Read sampled depth as its native IEEE-754 bits for GPU selection caches. */
void read_depth_region_uint(int mip, int layer, const int area[4], uint32_t *dst);
void update_sub(int mip,
int offset[3],
int extent[3],
eGPUDataFormat format,
const void *data,
uint row_length) override;
void update_sub(int offset[3], int extent[3], eGPUDataFormat format,
GPUPixelBuffer *buffer) override;
protected:
bool init_internal() override;
bool init_internal(VertBuf *) override;
bool init_internal(Texture *, int, int, bool) override;
};
} // namespace blender::gpu

View File

@@ -0,0 +1,29 @@
/* SPDX-FileCopyrightText: 2026 Blender Authors
*
* SPDX-License-Identifier: GPL-2.0-or-later */
#pragma once
#include "GPU_texture.hh"
#include "GPU_framebuffer.hh"
namespace blender::gpu {
/* Query storage without publishing pending writes. Native region owners must
* recapture GPU-only contents after browser context loss. Keep this query
* usable by WM without importing the GPU backend's private implementation. */
bool webgl_texture_has_live_storage(Texture *texture);
/* Query the native FBO name without binding or reattaching it. Auxiliary
* editor owners use this to retire a same-sized selection target after a
* browser context restore. */
bool webgl_framebuffer_has_live_storage(FrameBuffer *framebuffer);
/* The browser default framebuffer is owned by GHOST, but native WM readback still needs a
* backend-owned liveness check before sampling it after context restoration. */
bool webgl_frontbuffer_is_readable();
/* WM calls this only after GHOST presents a complete native editor frame. */
void webgl_frontbuffer_publish();
} // namespace blender::gpu

View File

@@ -0,0 +1,21 @@
/* SPDX-FileCopyrightText: 2026 Blender Authors
*
* SPDX-License-Identifier: GPL-2.0-or-later */
#pragma once
namespace blender::gpu {
/* Only synchronous editor tool-depth requests consume the WM interrupt signal.
* Keep normal render/compute texture transfers outside this cancellation scope.
* This caller interface deliberately needs no private GPU or GLES headers. */
class WebGLToolDepthScope {
public:
WebGLToolDepthScope();
~WebGLToolDepthScope();
WebGLToolDepthScope(const WebGLToolDepthScope &) = delete;
WebGLToolDepthScope &operator=(const WebGLToolDepthScope &) = delete;
};
void webgl_tool_depth_check_interrupt();
} // namespace blender::gpu