Blender V5.3
gpu_texture_mipmap.cc
Go to the documentation of this file.
1/* SPDX-FileCopyrightText: 2026 Blender Authors
2 *
3 * SPDX-License-Identifier: GPL-2.0-or-later */
4
8
9#include "BLI_bit_span.hh"
10#include "BLI_bit_span_ops.hh"
11#include "BLI_index_range.hh"
12#include "BLI_math_base_c.hh"
14#include "BLI_vector.hh"
15
16#include "GPU_capabilities.hh"
17#include "GPU_compute.hh"
18#include "GPU_debug.hh"
19#include "GPU_shader.hh"
20#include "GPU_shader_builtin.hh"
21#include "GPU_shader_shared.hh"
22#include "GPU_state.hh"
23#include "GPU_storage_buffer.hh"
24#include "GPU_texture.hh"
25
28#include "gpu_shader_private.hh"
30
31#include "CLG_log.h"
32
33static CLG_LogRef LOG = {"gpu.mipmap"};
34
35namespace blender {
36
37namespace gpu {
38
39static Shader *get_update_mipmap_shader(TextureFormat texture_format, bool is_layered)
40{
41 if (is_layered) {
42 switch (texture_format) {
43 case TextureFormat::UNORM_8:
45 case TextureFormat::UNORM_8_8_8_8:
47 case TextureFormat::SFLOAT_16:
49 case TextureFormat::SFLOAT_16_16_16_16:
52 case TextureFormat::SFLOAT_32:
54 case TextureFormat::SFLOAT_32_32_32_32:
57 case TextureFormat::SRGBA_8_8_8_8:
59 default:
60 break;
61 }
62 return nullptr;
63 }
64
65 switch (texture_format) {
66 case TextureFormat::UNORM_8:
68 case TextureFormat::UNORM_8_8_8_8:
70 case TextureFormat::SFLOAT_16:
72 case TextureFormat::SFLOAT_16_16_16_16:
74 case TextureFormat::SFLOAT_32:
76 case TextureFormat::SFLOAT_32_32_32_32:
78 case TextureFormat::SRGBA_8_8_8_8:
80 default:
81 break;
82 }
83 return nullptr;
84}
85
86/* Shader and API chunk size are assumed to match. */
87static_assert(GPU_TEXTURE_MIPMAP_UPDATE_CHUNK_SIZE == MIPMAP_UPDATE_CHUNK_SIZE);
88/* Chunk size is assumed power-of-two so footprint at every level is a whole
89 * number of destination tiles or within a single tile. */
92
95 const IndexRange layers,
96 const TextureFormat view_format,
97 const BitSpan modified_chunks)
98{
99 const int num_mipmaps = texture.mip_count();
100 const int layer_count = texture.layer_count();
101
102 /* Create view for each mipmap level. Profiling shows this is the most expensive
103 * host side work of GPU mipmap generation, so it may be worth trying to cache this.
104 * But it may not be that significant compared to e.g. other texture painting
105 * overhead, needs to be measured. */
107 for (int mipmap : IndexRange(num_mipmaps)) {
108 views.append(GPU_texture_create_view(
109 __func__, &texture, view_format, mipmap, 1, 0, layer_count, false, false));
110 }
111
112 /* Check the bitmask has the correct size, or empty for full update. */
113 const int2 chunks_size(
116 BLI_assert(modified_chunks.is_empty() ||
117 modified_chunks.size() == chunks_size.x * chunks_size.y);
118
119 /* Turn bitmask into chunk coordinates. */
120 Vector<int2> chunks;
121 bits::foreach_1_index(modified_chunks, [&](const int64_t i) {
122 chunks.append(int2(i % chunks_size.x, i / chunks_size.x));
123 });
124 StorageBuf *chunk_buf = GPU_storagebuf_create_ex(sizeof(int2) * max_ii(chunks.size(), 1),
125 chunks.is_empty() ? nullptr : chunks.data(),
127 __func__);
128 GPU_storagebuf_bind(chunk_buf, GPU_shader_get_ssbo_binding(&shader, "chunk_list"));
129
130 /* The views cover all layers, so only the destination layer of the dispatch varies. */
131 const auto compute_dispatch_layers =
132 [&](const int groups_x, const int groups_y, const int groups_z) {
133 for (const int64_t layer : layers) {
134 GPU_shader_uniform_1i(&shader, "dst_layer", int(layer));
135 GPU_compute_dispatch(&shader, groups_x, groups_y, groups_z);
136 }
137 };
138
139 constexpr int max_levels_per_dispatch = 2;
140
141 for (int mip_start = 0; mip_start < num_mipmaps - 1; mip_start += max_levels_per_dispatch) {
143 GPU_texture_image_bind(views[mip_start], 0);
144 for (int mip_offset = 1; mip_offset <= max_levels_per_dispatch; mip_offset++) {
145 GPU_texture_image_bind(views[min_ii(mip_start + mip_offset, views.size() - 1)], mip_offset);
146 }
147 int num_levels = min_ii(views.size() - mip_start - 1, max_levels_per_dispatch);
148 GPU_shader_uniform_1i(&shader, "num_levels", num_levels);
149
150 int3 mip_size(1, 1, 1);
151 texture.mip_size_get(mip_start + num_levels, mip_size);
152
153 if (num_levels == 1u) {
154 /* Each thread writes one sample. */
155 constexpr uint32_t warps = 4;
156 const uint32_t samples = mip_size.x * mip_size.y;
157 const uint32_t threads = warps * 32U;
158 const uint group_len = divide_ceil_u(samples, threads);
159
160 /* The number of work groups in a single dispatch is bounded by `GPU_max_work_group_count()`.
161 * Split the work over multiple dispatches when it doesn't fit. */
162 const int max_group_count = max_ii(GPU_max_work_group_count(0), 1);
163 for (uint group_offset = 0; group_offset < group_len; group_offset += max_group_count) {
164 GPU_shader_uniform_1i(&shader, "group_offset", int(group_offset));
165 compute_dispatch_layers(int(min_uu(group_len - group_offset, max_group_count)), 1, 1);
166 }
167 continue;
168 }
169
170 /* Each workgroup handles a tile. */
171 const int2 tile_count(divide_ceil_u(mip_size.x, MIPMAP_UPDATE_TILE_SIZE),
172 divide_ceil_u(mip_size.y, MIPMAP_UPDATE_TILE_SIZE));
173
174 if (!chunks.is_empty()) {
175 /* Partial update. */
176 const int dst_level = mip_start + num_levels;
177
178 /* Add a margin for levels with odd dimensions, as neighboring chunks are affected then.
179 * For the common case of power-of-two textures there is no margin needed because of the
180 * simple box filter. */
181 int2 margin(0, 0);
182 for (const int src_level : IndexRange(dst_level)) {
183 int3 src_size(1, 1, 1);
184 texture.mip_size_get(src_level, src_size);
185 margin.x |= (src_size.x > 1 && (src_size.x & 1));
186 margin.y |= (src_size.y > 1 && (src_size.y & 1));
187 }
188
189 /* A tile grid is dispatched per chunk. It covers the chunk's footprint at dst_level,
190 * plus the margin. */
191 const int chunk_pixels_num = max_ii(GPU_TEXTURE_MIPMAP_UPDATE_CHUNK_SIZE >> dst_level, 1);
192 const auto chunk_tiles_num = [&](const int margin) {
193 return margin ? int(divide_ceil_u(chunk_pixels_num + 2, MIPMAP_UPDATE_TILE_SIZE)) + 1 :
194 max_ii(chunk_pixels_num / MIPMAP_UPDATE_TILE_SIZE, 1);
195 };
196 const int2 sub_tiles(chunk_tiles_num(margin.x), chunk_tiles_num(margin.y));
197
198 /* Check if we already cover the whole level anyway, if so fall through to full update. */
199 const int64_t total_tiles = int64_t(tile_count.x) * tile_count.y;
200 if (chunks.size() * sub_tiles.x * sub_tiles.y < total_tiles) {
201 /* Partial update, one workgroup per tile in a chunk. */
202 GPU_shader_uniform_1i(&shader, "partial_dst_level", dst_level);
203 GPU_shader_uniform_1i(&shader, "margin_x", margin.x);
204 GPU_shader_uniform_1i(&shader, "margin_y", margin.y);
205 compute_dispatch_layers(sub_tiles.x, sub_tiles.y, chunks.size());
206 continue;
207 }
208 }
209
210 /* Full update, one workgroup per tile. */
211 GPU_shader_uniform_1i(&shader, "partial_dst_level", -1);
212 GPU_shader_uniform_1i(&shader, "margin_x", 0);
213 GPU_shader_uniform_1i(&shader, "margin_y", 0);
214 compute_dispatch_layers(tile_count.x, tile_count.y, 1);
215 }
216
217 for (Texture *view : views) {
218 GPU_texture_free(view);
219 }
220 GPU_storagebuf_unbind(chunk_buf);
221 GPU_storagebuf_free(chunk_buf);
223}
224
226 Shader &shader,
227 const TextureFormat write_format,
228 const int partial_layer,
229 const BitSpan modified_chunks)
230{
231 Context &context = *Context::get();
232 Shader *prev_shader = context.shader;
233
234 Texture *texture_ptr = &texture;
235 const int layer_count = texture.layer_count();
236 const int mip_count = texture.mip_count();
237 const bool is_layered = texture.type_get() & GPU_TEXTURE_ARRAY;
238
239 /* When the texture format can not be written to directly and we can't use a view
240 * to write it as another format, use a temporary texture. */
241 const bool use_temp_texture = write_format != texture.format_get() &&
242 (texture.usage_get() & GPU_TEXTURE_USAGE_FORMAT_VIEW) == 0;
243 if (use_temp_texture) {
244 if (is_layered) {
245 texture_ptr = GPU_texture_create_2d_array(__func__,
246 texture.width_get(),
247 texture.height_get(),
248 layer_count,
249 texture.mip_count(),
250 TextureFormat::UNORM_8_8_8_8,
253 nullptr);
254 }
255 else {
256 texture_ptr = GPU_texture_create_2d(__func__,
257 texture.width_get(),
258 texture.height_get(),
259 texture.mip_count(),
260 TextureFormat::UNORM_8_8_8_8,
263 nullptr);
264 }
265 texture.copy_to(texture_ptr, IndexRange(1));
266 }
267
269
270 if (modified_chunks.is_empty() || use_temp_texture) {
271 /* Full update of every layer. The temporary texture path does not currently
272 * support partial updates, but image textures request #GPU_TEXTURE_USAGE_FORMAT_VIEW for
273 * the formats that would need it, so painting does not reach this. */
274 update_mipmaps_layers(*texture_ptr, shader, IndexRange(layer_count), write_format, {});
275 }
276 else {
277 /* Partial update of a single layer's changed chunks. */
278 update_mipmaps_layers(*texture_ptr,
279 shader,
280 IndexRange::from_single(partial_layer),
281 write_format,
282 modified_chunks);
283 }
284
285 if (use_temp_texture) {
286 /* Copy result (mip1 and higher) to original texture and free temporary resources. */
287 texture_ptr->copy_to(&texture, IndexRange::from_begin_end(1, mip_count));
288 GPU_texture_free(texture_ptr);
289 texture_ptr = nullptr;
290 }
291
292 /* Clear all bound images.
293 *
294 * Current OpenGL API doesn't have a way to rebind the previous state as it only keeps track of
295 * handles. Using a temporary state manager doesn't fit with Metal as the state is stored in
296 * multiple places.
297 *
298 * To not over complicate the implementation for something that is not likely to happen it was
299 * decided to unbind all images. When artifacts happen the calling code must be fixed. */
300 context.state_manager->image_unbind_all();
301
302 /* Reset original state. */
303 if (prev_shader) {
304 GPU_shader_bind(prev_shader);
305 }
306}
307
308} // namespace gpu
309
310using namespace blender::gpu;
311
313{
314 /* Mipmaps generated with the compute shader need write support. */
316
317 /* If it's sRGB and we can't write directly to it, use a texture view to write through. */
318 if (format == TextureFormat::SRGBA_8_8_8_8) {
321 }
322 }
323
324 return usage;
325}
326
328 const int partial_layer,
329 const BitSpan modified_chunks)
330{
331 BLI_assert(tex);
332
333 const int num_mipmaps = tex->mip_count();
334 /* Early exit - nothing to generate as texture only contains 1 mipmap level. */
335 if (num_mipmaps == 1) {
336 return;
337 }
338
339 bool use_compute_shaders = true;
340
341 if ((tex->usage_get() & GPU_TEXTURE_USAGE_SHADER_WRITE) == 0) {
343 "Texture doesn't have `GPU_TEXTURE_USAGE_SHADER_WRITE` set. Fallback to backend "
344 "implementation");
345 use_compute_shaders = false;
346 }
347
348 if (use_compute_shaders) {
349 const TextureFormat texture_format = tex->format_get();
350 const bool is_layered = tex->type_get() & GPU_TEXTURE_ARRAY;
351 const bool is_srgb = texture_format == TextureFormat::SRGBA_8_8_8_8;
352 /* For sRGB without direct write support, write with a UNORM_8_8_8_8 format,
353 * either in a temporary texture or through a texture view. */
354 const TextureFormat write_format = (is_srgb && !GCaps.srgb_write_direct_support) ?
355 TextureFormat::UNORM_8_8_8_8 :
356 texture_format;
357 /* For sRGB with direct write support, the shader is that same as UNORM_8_8_8_8 and
358 * any conversion to/from sRGB happens automatically. */
359 const TextureFormat shader_format = (is_srgb && GCaps.srgb_write_direct_support) ?
360 TextureFormat::UNORM_8_8_8_8 :
361 texture_format;
362 Shader *shader = get_update_mipmap_shader(shader_format, is_layered);
363 if (shader) {
364 GPU_debug_group_begin("Update Mipmaps");
365 update_mipmaps(*tex, *shader, write_format, partial_layer, modified_chunks);
367 return;
368 }
369 CLOG_INFO(&LOG,
370 "No shader exists for updating mipmaps (format=%s). Fallback to backend "
371 "implementation, this could lead to different results between platforms.",
372 GPU_texture_format_name(texture_format));
373 }
374
375 /* No mipmap shader exists for this texture format. Fallback to backend implementation. */
376 tex->generate_mipmap();
377}
378
383
385 const int layer,
386 const BitSpan modified_chunks)
387{
388 if (bits::any_bit_set(modified_chunks)) {
389 texture_update_mipmap_chain(tex, layer, modified_chunks);
390 }
391}
392
393} // namespace blender
#define CLOG_TRACE(clg_ref,...)
Definition CLG_log.h:192
#define CLOG_INFO(clg_ref,...)
Definition CLG_log.h:190
static constexpr IndexRange from_begin_end(const int64_t begin, const int64_t end)
constexpr IndexRange()=default
static constexpr IndexRange from_single(const int64_t index)
static Context * get()
virtual void copy_to(Texture *tex, IndexRange mip_levels)=0
#define layer
TEX_TEMPLATE DataVec texture(T, FltCoord, float=0.0f) RET
#define LOG(level)
Definition log.h:97
bool any_bit_set(const BitSpanT &arg)
void foreach_1_index(const BitSpanT &data, Fn &&fn)
static void update_mipmaps_layers(Texture &texture, Shader &shader, const IndexRange layers, const TextureFormat view_format, const BitSpan modified_chunks)
static Shader * get_update_mipmap_shader(TextureFormat texture_format, bool is_layered)
GPUCapabilities GCaps
static void update_mipmaps(Texture &texture, Shader &shader, const TextureFormat write_format, const int partial_layer, const BitSpan modified_chunks)
BMesh Iterators.
BLI_assert(slot->slot_subtype.map==BMO_OP_SLOT_SUBTYPE_MAP_FLT)
__int64 int64_t
Definition BKE_text.h:90
unsigned int uint
Definition BKE_text.h:55
gpu::StorageBuf * GPU_storagebuf_create_ex(size_t size, const void *data, GPUUsageType usage, const char *name)
void GPU_texture_update_mipmap_chain(gpu::Texture *texture)
constexpr int GPU_TEXTURE_MIPMAP_UPDATE_CHUNK_SIZE
gpu::Texture * GPU_texture_create_2d_array(const char *name, int width, int height, int layer_len, int mip_len, gpu::TextureFormat format, eGPUTextureUsage usage, const float *data)
MINLINE int max_ii(int a, int b)
void GPU_compute_dispatch(gpu::Shader *shader, uint groups_x_len, uint groups_y_len, uint groups_z_len, const gpu::shader::SpecializationConstants *constants_state=nullptr)
int GPU_shader_get_ssbo_binding(gpu::Shader *shader, const char *name)
int GPU_max_work_group_count(int index)
unsigned int uint32_t
Definition BKE_text.h:81
VecBase< int32_t, 2 > int2
VecBase< int32_t, 3 > int3
@ GPU_TEXTURE_USAGE_FORMAT_VIEW
@ GPU_TEXTURE_USAGE_SHADER_READ
@ GPU_TEXTURE_USAGE_SHADER_WRITE
void GPU_memory_barrier(GPUBarrier barrier)
Definition gpu_state.cc:305
@ GPU_SHADER_2D_UPDATE_MIPMAPS_SFLOAT_16_16_16_16
@ GPU_SHADER_2D_UPDATE_MIPMAPS_SFLOAT_32_32_32_32_LAYERED
@ GPU_SHADER_2D_UPDATE_MIPMAPS_SRGBA_8_8_8_8_LAYERED
@ GPU_SHADER_2D_UPDATE_MIPMAPS_UNORM_8_8_8_8
@ GPU_SHADER_2D_UPDATE_MIPMAPS_SFLOAT_32_LAYERED
@ GPU_SHADER_2D_UPDATE_MIPMAPS_UNORM_8
@ GPU_SHADER_2D_UPDATE_MIPMAPS_SRGBA_8_8_8_8
@ GPU_SHADER_2D_UPDATE_MIPMAPS_SFLOAT_32
@ GPU_SHADER_2D_UPDATE_MIPMAPS_SFLOAT_16_16_16_16_LAYERED
@ GPU_SHADER_2D_UPDATE_MIPMAPS_SFLOAT_16_LAYERED
@ GPU_SHADER_2D_UPDATE_MIPMAPS_UNORM_8_LAYERED
@ GPU_SHADER_2D_UPDATE_MIPMAPS_SFLOAT_16
@ GPU_SHADER_2D_UPDATE_MIPMAPS_UNORM_8_8_8_8_LAYERED
@ GPU_SHADER_2D_UPDATE_MIPMAPS_SFLOAT_32_32_32_32
void GPU_texture_update_mipmap_chain_partial(gpu::Texture *texture, int layer, BitSpan modified_chunks)
void GPU_shader_bind(gpu::Shader *shader, const gpu::shader::SpecializationConstants *constants_state=nullptr)
void GPU_shader_uniform_1i(gpu::Shader *sh, const char *name, int value)
@ GPU_BARRIER_TEXTURE_FETCH
Definition GPU_state.hh:40
@ GPU_BARRIER_SHADER_IMAGE_ACCESS
Definition GPU_state.hh:38
void GPU_storagebuf_bind(gpu::StorageBuf *ssbo, int slot)
void GPU_storagebuf_unbind(gpu::StorageBuf *ssbo)
void GPU_debug_group_end()
Definition gpu_debug.cc:34
gpu::Shader * GPU_shader_get_builtin_shader(GPUBuiltinShader shader)
static void texture_update_mipmap_chain(Texture *tex, const int partial_layer, const BitSpan modified_chunks)
void GPU_texture_free(gpu::Texture *texture)
MINLINE uint divide_ceil_u(uint a, uint b)
const char * GPU_texture_format_name(gpu::TextureFormat format)
void GPU_texture_image_bind(gpu::Texture *texture, int unit)
void GPU_storagebuf_free(gpu::StorageBuf *ssbo)
gpu::Texture * GPU_texture_create_view(const char *name, gpu::Texture *source_texture, gpu::TextureFormat view_format, int mip_start, int mip_len, int layer_start, int layer_len, bool cube_as_array, bool use_stencil)
MINLINE int min_ii(int a, int b)
gpu::Texture * GPU_texture_create_2d(const char *name, int width, int height, int mip_len, gpu::TextureFormat format, eGPUTextureUsage usage, const float *data)
void GPU_debug_group_begin(const char *name)
Definition gpu_debug.cc:23
MINLINE uint min_uu(uint a, uint b)
eGPUTextureUsage GPU_texture_mipmap_usage(gpu::TextureFormat format)
int size() const
Definition vector.hh:130