Blender V5.3
gl_texture.cc
Go to the documentation of this file.
1/* SPDX-FileCopyrightText: 2020 Blender Authors
2 *
3 * SPDX-License-Identifier: GPL-2.0-or-later */
4
8
9#include <cstdint>
10#include <string>
11
12#include "BLI_assert.hh"
13#include "BLI_math_half.hh"
14#include "BLI_string.hh"
15
16#include "DNA_userdef_types.h"
17
18#include "GPU_capabilities.hh"
19#include "GPU_framebuffer.hh"
20#include "GPU_platform.hh"
21
22#include "GPU_vertex_buffer.hh" /* TODO: should be `gl_vertex_buffer.hh`. */
23#include "MEM_guardedalloc.h"
24#include "gl_backend.hh"
25#include "gl_debug.hh"
26#include "gl_state.hh"
28
29#include "gl_texture.hh"
30
31namespace blender::gpu {
32
33/* -------------------------------------------------------------------- */
36
37GLTexture::GLTexture(const char *name) : Texture(name)
38{
39 BLI_assert(GLContext::get() != nullptr);
40
41 glGenTextures(1, &tex_id_);
42}
43
45{
46 if (framebuffer_) {
47 GPU_framebuffer_free(framebuffer_);
48 }
50 if (ctx != nullptr && (is_bound_ || is_bound_image_)) {
51 /* This avoid errors when the texture is still inside the bound texture/image array. */
52 ctx->state_manager->texture_unbind(this);
53 ctx->state_manager->image_unbind(this);
54 }
56}
57
59{
60 target_ = to_gl_target(type_);
61
62 /* We need to bind once to define the texture type. */
64
65 if (!this->proxy_check(0)) {
66 return false;
67 }
68
69 GLenum internal_format = to_gl_internal_format(format_);
70 const bool is_cubemap = bool(type_ == GPU_TEXTURE_CUBE);
71 const int dimensions = (is_cubemap) ? 2 : this->dimensions_count();
72
73 switch (dimensions) {
74 default:
75 case 1:
76 glTexStorage1D(target_, mipmaps_, internal_format, w_);
77 break;
78 case 2:
79 glTexStorage2D(target_, mipmaps_, internal_format, w_, h_);
80 break;
81 case 3:
82 glTexStorage3D(target_, mipmaps_, internal_format, w_, h_, d_);
83 break;
84 }
85 this->mip_range_set(0, mipmaps_ - 1);
86
87 /* Avoid issue with formats not supporting filtering. Nearest by default. */
89 glTextureParameteri(tex_id_, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
90 }
91 else {
92 glTexParameteri(target_, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
93 }
94
95 debug::object_label(GL_TEXTURE, tex_id_, name_.c_str());
96 return true;
97}
98
100{
101 GLVertBuf *gl_vbo = static_cast<GLVertBuf *>(vbo);
102 target_ = to_gl_target(type_);
103
104 /* We need to bind once to define the texture type. */
106
107 GLenum internal_format = to_gl_internal_format(format_);
108
110 glTextureBuffer(tex_id_, internal_format, gl_vbo->vbo_id_);
111 }
112 else {
113 glTexBuffer(target_, internal_format, gl_vbo->vbo_id_);
114 }
115
116 debug::object_label(GL_TEXTURE, tex_id_, name_.c_str());
117
118 return true;
119}
120
121bool GLTexture::init_internal(gpu::Texture *src, bool use_stencil)
122{
123 const GLTexture *gl_src = static_cast<const GLTexture *>(src);
124 GLenum internal_format = to_gl_internal_format(format_);
125 target_ = to_gl_target(type_);
126
127 glTextureView(tex_id_,
128 target_,
129 gl_src->tex_id_,
130 internal_format,
131 mip_min_,
132 mipmaps_,
134 layer_count());
135
136 debug::object_label(GL_TEXTURE, tex_id_, name_.c_str());
137
138 /* Stencil view support. */
139 if (ELEM(format_, TextureFormat::SFLOAT_32_DEPTH_UINT_8)) {
140 stencil_texture_mode_set(use_stencil);
141 }
142
143 return true;
144}
145
147
148/* -------------------------------------------------------------------- */
151
152void GLTexture::update_sub_direct_state_access(
153 int mip, int offset[3], int extent[3], GLenum format, GLenum type, const void *data)
154{
156 size_t size = ((extent[0] + 3) / 4) * ((extent[1] + 3) / 4) * to_block_size(format_);
157 switch (this->dimensions_count()) {
158 default:
159 case 1:
160 glCompressedTextureSubImage1D(tex_id_, mip, offset[0], extent[0], format, size, data);
161 break;
162 case 2:
163 glCompressedTextureSubImage2D(
164 tex_id_, mip, UNPACK2(offset), UNPACK2(extent), format, size, data);
165 break;
166 case 3:
167 glCompressedTextureSubImage3D(
168 tex_id_, mip, UNPACK3(offset), UNPACK3(extent), format, size, data);
169 break;
170 }
171 }
172 else {
173 switch (this->dimensions_count()) {
174 default:
175 case 1:
176 glTextureSubImage1D(tex_id_, mip, offset[0], extent[0], format, type, data);
177 break;
178 case 2:
179 glTextureSubImage2D(tex_id_, mip, UNPACK2(offset), UNPACK2(extent), format, type, data);
180 break;
181 case 3:
182 glTextureSubImage3D(tex_id_, mip, UNPACK3(offset), UNPACK3(extent), format, type, data);
183 break;
184 }
185 }
186
187 has_pixels_ = true;
188}
189
191 int offset[3],
192 int extent[3],
193 eGPUDataFormat type,
194 const void *data,
195 const uint unpack_row_length)
196{
198 BLI_assert(data != nullptr);
199
200 if (mip >= mipmaps_) {
201 debug::raise_gl_error("Updating a miplvl on a texture too small to have this many levels.");
202 return;
203 }
204
205 /* If `unpack_row_length` is 0, rows are sequentially stored. Otherwise we unpack data
206 * into a staging block, so the half conversion below doesn't happen on the full input. */
207 const bool do_texture_unpack = !ELEM(unpack_row_length, 0, extent[0]);
208
209 /* Unpack `data` if `unpack_row_length` is set. */
210 std::unique_ptr<uint8_t, MEM_smart_ptr_deleter<uint8_t>> unpack_buffer = nullptr;
211 if (do_texture_unpack) {
213 "Compressed data with unpack_row_length != 0 is not supported.");
214 BLI_assert_msg(extent[2] <= 1,
215 "3D texture data with unpack_row_length != 0 is not supported.");
216
217 size_t src_row_stride = unpack_row_length * to_bytesize(format_, type);
218 size_t dst_row_stride = max_ii(extent[0], 1) * to_bytesize(format_, type);
219 size_t dst_total_count = dst_row_stride * max_ii(extent[1], 1) * max_ii(extent[2], 1);
220
221 /* Allocate buffer to size necessary for gather */
222 unpack_buffer.reset(
223 static_cast<uint8_t *>(MEM_new_uninitialized_aligned(dst_total_count, 128, __func__)));
224
225 /* Strided loop; we advance source and destination pointers separately during a gather. */
226 const uint8_t *src_ptr = static_cast<const uint8_t *>(data);
227 uint8_t *dst_ptr = unpack_buffer.get();
228 for (int y = 0; y < max_ii(extent[1], 1); ++y) {
229 std::memcpy(dst_ptr, src_ptr, dst_row_stride);
230 src_ptr += src_row_stride;
231 dst_ptr += dst_row_stride;
232 }
233
234 /* Replace the 'data' ptr with `unpack_buffer`,
235 * which has lifetime in the function scope. */
236 data = unpack_buffer.get();
237 }
238
239 GLenum gl_type = to_gl(type);
240
241 /* If `data` is float and target storage is half, convert to half */
242 std::unique_ptr<uint16_t, MEM_smart_ptr_deleter<uint16_t>> clamped_half_buffer = nullptr;
243 if (type == GPU_DATA_FLOAT && is_half_float(format_)) {
244 size_t dst_pixel_count = max_ii(extent[0], 1) * max_ii(extent[1], 1) * max_ii(extent[2], 1);
245 size_t dst_total_count = to_component_len(format_) * dst_pixel_count;
246
247 /* Allocate buffer to size necessary for conversion.. */
248 clamped_half_buffer.reset(static_cast<uint16_t *>(
249 MEM_new_uninitialized_aligned(sizeof(uint16_t) * dst_total_count, 128, __func__)));
250
251 Span<float> src(static_cast<const float *>(data), dst_total_count);
252 MutableSpan<uint16_t> dst(static_cast<uint16_t *>(clamped_half_buffer.get()), dst_total_count);
253
254 constexpr int64_t chunk_size = 4 * 1024 * 1024;
255 threading::parallel_for(IndexRange(dst_total_count), chunk_size, [&](const IndexRange range) {
256 /* Doing float to half conversion manually to avoid implementation specific behavior
257 * regarding Inf and NaNs. Use make finite version to avoid unexpected black pixels on
258 * certain implementation. For platform parity we clamp these infinite values to finite
259 * values. */
261 src.slice(range).data(), dst.slice(range).data(), range.size());
262 });
263
264 /* Replace the 'data' ptr with `clamped_half_buffer`,
265 * which has lifetime in the function scope. */
266 data = clamped_half_buffer.get();
267 gl_type = to_gl(GPU_DATA_HALF_FLOAT);
268
269 /* If the `data` ptr was previously replaced by `unpack_buffer`,
270 * clear `unpack_buffer` as it is no longer necessary. */
271 if (do_texture_unpack) {
272 unpack_buffer.reset(nullptr);
273 }
274 }
275
276 /* 16-bit integer formats with integer data does not seem to work correctly in all GPU drivers,
277 * so convert to short and use GL_SHORT. */
278 std::unique_ptr<int16_t, MEM_smart_ptr_deleter<int16_t>> short_buffer = nullptr;
279 if (type == GPU_DATA_INT && is_half_integer(format_)) {
280 size_t dst_pixel_count = max_ii(extent[0], 1) * max_ii(extent[1], 1) * max_ii(extent[2], 1);
281 size_t dst_total_count = to_component_len(format_) * dst_pixel_count;
282
283 short_buffer.reset(static_cast<int16_t *>(
284 MEM_new_uninitialized_aligned(sizeof(int16_t) * dst_total_count, 128, __func__)));
285
286 Span<int32_t> src(static_cast<const int32_t *>(data), dst_total_count);
287 MutableSpan<int16_t> dst(static_cast<int16_t *>(short_buffer.get()), dst_total_count);
288
289 constexpr int64_t chunk_size = 4 * 1024 * 1024;
290 threading::parallel_for(IndexRange(dst_total_count), chunk_size, [&](const IndexRange range) {
291 for (const int64_t i : range) {
292 dst[i] = int16_t(src[i]);
293 }
294 });
295
296 /* Replace the 'data' ptr with `short_buffer`, which has lifetime in the function scope. */
297 data = short_buffer.get();
298 gl_type = GL_SHORT;
299
300 /* If the `data` ptr was previously replaced by `unpack_buffer`,
301 * clear `unpack_buffer` as it is no longer necessary. */
302 if (do_texture_unpack) {
303 unpack_buffer.reset(nullptr);
304 }
305 }
306
307 const int dimensions = this->dimensions_count();
308 GLenum gl_format = to_gl_data_format(format_);
309
310 /* Some drivers have issues with cubemap & glTextureSubImage3D even if it is correct. */
312 this->update_sub_direct_state_access(mip, offset, extent, gl_format, gl_type, data);
313 return;
314 }
315
317 if (type_ == GPU_TEXTURE_CUBE) {
318 for (int i = 0; i < extent[2]; i++) {
319 GLenum target = GL_TEXTURE_CUBE_MAP_POSITIVE_X + offset[2] + i;
320 glTexSubImage2D(target, mip, UNPACK2(offset), UNPACK2(extent), gl_format, gl_type, data);
321 }
322 }
324 size_t size = ((extent[0] + 3) / 4) * ((extent[1] + 3) / 4) * to_block_size(format_);
325 switch (dimensions) {
326 default:
327 case 1:
328 glCompressedTexSubImage1D(target_, mip, offset[0], extent[0], gl_format, size, data);
329 break;
330 case 2:
331 glCompressedTexSubImage2D(
332 target_, mip, UNPACK2(offset), UNPACK2(extent), gl_format, size, data);
333 break;
334 case 3:
335 glCompressedTexSubImage3D(
336 target_, mip, UNPACK3(offset), UNPACK3(extent), gl_format, size, data);
337 break;
338 }
339 }
340 else {
341 switch (dimensions) {
342 default:
343 case 1:
344 glTexSubImage1D(target_, mip, offset[0], extent[0], gl_format, gl_type, data);
345 break;
346 case 2:
347 glTexSubImage2D(target_, mip, UNPACK2(offset), UNPACK2(extent), gl_format, gl_type, data);
348 break;
349 case 3:
350 glTexSubImage3D(target_, mip, UNPACK3(offset), UNPACK3(extent), gl_format, gl_type, data);
351 break;
352 }
353 }
354
355 has_pixels_ = true;
356}
357
358void GLTexture::update_sub(int offset[3],
359 int extent[3],
360 eGPUDataFormat format,
361 GPUPixelBuffer *pixbuf)
362{
363 /* Update texture from pixel buffer. */
365 BLI_assert(pixbuf != nullptr);
366
367 const int dimensions = this->dimensions_count();
368 GLenum gl_format = to_gl_data_format(format_);
369 GLenum gl_type = to_gl(format);
370
371 /* Temporarily Bind texture. */
373
374 /* Bind pixel buffer for source data. */
375 GLint pix_buf_handle = GLint(GPU_pixel_buffer_get_native_handle(pixbuf).handle);
376 glBindBuffer(GL_PIXEL_UNPACK_BUFFER, pix_buf_handle);
377
378 switch (dimensions) {
379 default:
380 case 1:
381 glTexSubImage1D(target_, 0, offset[0], extent[0], gl_format, gl_type, nullptr);
382 break;
383 case 2:
384 glTexSubImage2D(target_, 0, UNPACK2(offset), UNPACK2(extent), gl_format, gl_type, nullptr);
385 break;
386 case 3:
387 glTexSubImage3D(target_, 0, UNPACK3(offset), UNPACK3(extent), gl_format, gl_type, nullptr);
388 break;
389 }
390
391 glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);
392}
393
395{
396 /* Allow users to provide mipmaps stored in compressed textures.
397 * Skip generating mipmaps to avoid overriding the existing ones. */
399 return;
400 }
401
402 /* Some drivers have bugs when using #glGenerateMipmap with depth textures (see #56789).
403 * In this case we just create a complete texture with mipmaps manually without
404 * down-sampling. You must initialize the texture levels using other methods. */
406 return;
407 }
408
409 /* Down-sample from mip 0 using implementation. */
411 glGenerateTextureMipmap(tex_id_);
412 }
413 else {
415 glGenerateMipmap(target_);
416 }
417}
418
420{
421 /* Note: do not use glClearTexImage, even if it is available (via
422 * extension or GL 4.4). It causes GL framebuffer binding to be
423 * way slower at least on some drivers (e.g. Win10 / NV RTX 3080,
424 * but also reportedly others), as if glClearTexImage causes
425 * "pixel data" to exist which is then uploaded CPU -> GPU at bind
426 * time. */
427
429
430 /* fb->clear_attachment only affects one mip level. Iterate in reverse order so at the end, mip
431 * level 0 is bound to the framebuffer. */
432 for (int mip = mipmaps_ - 1; mip >= 0; mip--) {
433 FrameBuffer *fb = this->framebuffer_get(mip);
434 fb->bind(true);
435 fb->clear_attachment(this->attachment_type(0), data);
436 }
437
438 GPU_framebuffer_bind(prev_fb);
439}
440
441void GLTexture::copy_to(Texture *dst_, IndexRange mip_levels)
442{
443 GLTexture *dst = static_cast<GLTexture *>(dst_);
444 GLTexture *src = this;
445
446 BLI_assert(src->w_ == dst->w_ && std::max(src->h_, 1) == std::max(dst->h_, 1) &&
447 std::max(src->d_, 1) == std::max(dst->d_, 1));
448 BLI_assert((src->format_ == dst->format_) ||
449 (src->format_ == TextureFormat::SRGBA_8_8_8_8 &&
450 dst->format_ == TextureFormat::UNORM_8_8_8_8) ||
451 (src->format_ == TextureFormat::UNORM_8_8_8_8 &&
452 dst->format_ == TextureFormat::SRGBA_8_8_8_8));
454
455 /* Some drivers have issues with texture views, always make the copy using parent textures. */
456 GLTexture *dst_parent = dst->source_texture_ ? static_cast<GLTexture *>(dst->source_texture_) :
457 dst;
458 GLTexture *src_parent = src->source_texture_ ? static_cast<GLTexture *>(src->source_texture_) :
459 src;
460
461 for (int mip : mip_levels) {
462 /* NOTE: mip_size_get() won't override any dimension that is equal to 0. */
463 int extent[3] = {1, 1, 1};
464 this->mip_size_get(mip, extent);
465 glCopyImageSubData(src_parent->tex_id_,
466 src_parent->target_,
467 mip + src->mip_min_,
468 0,
469 (src->type_ & GPU_TEXTURE_1D) ? src->view_layer_start_ : 0,
470 (src->type_ & GPU_TEXTURE_1D) ? 0 : src->view_layer_start_,
471 dst_parent->tex_id_,
472 dst_parent->target_,
473 mip + dst->mip_min_,
474 0,
475 (dst->type_ & GPU_TEXTURE_1D) ? dst->view_layer_start_ : 0,
476 (dst->type_ & GPU_TEXTURE_1D) ? 0 : dst->view_layer_start_,
477 UNPACK3(extent));
478 }
479
480 has_pixels_ = true;
481}
482
483void GLTexture::read(int mip, eGPUDataFormat type, void *data)
484{
486 BLI_assert(mip <= mipmaps_ || mip == 0);
488
489 size_t texture_size = read_size_get(mip, type);
490 GLenum gl_format = to_gl_data_format(
491 format_ == TextureFormat::SFLOAT_32_DEPTH_UINT_8 ? TextureFormat::SFLOAT_32_DEPTH : format_);
492 GLenum gl_type = to_gl(type);
493
494 const int3 extent = mip_size_get(mip);
495
497 /* Read from the source texture, since OpenGL drivers don't seem to handle dimensions well,
498 * but this only works if the view and the texture formats match. */
499 glGetTextureSubImage(static_cast<GLTexture *>(source_texture_)->tex_id_,
500 mip + mip_min_,
501 0,
504 extent.x,
505 extent.y,
506 extent.z,
507 gl_format,
508 gl_type,
509 texture_size,
510 data);
511 }
512 else {
513 glGetTextureSubImage(tex_id_,
514 mip,
515 0,
516 0,
517 0,
518 extent.x,
519 extent.y,
520 extent.z,
521 gl_format,
522 gl_type,
523 texture_size,
524 data);
525 }
526}
527
529
530/* -------------------------------------------------------------------- */
533
534void GLTexture::swizzle_set(const char swizzle[4])
535{
536 GLint gl_swizzle[4] = {GLint(swizzle_to_gl(swizzle[0])),
537 GLint(swizzle_to_gl(swizzle[1])),
538 GLint(swizzle_to_gl(swizzle[2])),
539 GLint(swizzle_to_gl(swizzle[3]))};
541 glTextureParameteriv(tex_id_, GL_TEXTURE_SWIZZLE_RGBA, gl_swizzle);
542 }
543 else {
545 glTexParameteriv(target_, GL_TEXTURE_SWIZZLE_RGBA, gl_swizzle);
546 }
547}
548
549void GLTexture::stencil_texture_mode_set(bool use_stencil)
550{
552 GLint value = use_stencil ? GL_STENCIL_INDEX : GL_DEPTH_COMPONENT;
554 glTextureParameteri(tex_id_, GL_DEPTH_STENCIL_TEXTURE_MODE, value);
555 }
556 else {
558 glTexParameteri(target_, GL_DEPTH_STENCIL_TEXTURE_MODE, value);
559 }
560}
561
562void GLTexture::mip_range_set(int min, int max)
563{
565 mip_min_ = min;
566 mip_max_ = max;
568 glTextureParameteri(tex_id_, GL_TEXTURE_BASE_LEVEL, min);
569 glTextureParameteri(tex_id_, GL_TEXTURE_MAX_LEVEL, max);
570 }
571 else {
573 glTexParameteri(target_, GL_TEXTURE_BASE_LEVEL, min);
574 glTexParameteri(target_, GL_TEXTURE_MAX_LEVEL, max);
575 }
576}
577
578FrameBuffer *GLTexture::framebuffer_get(int mip)
579{
580 if (framebuffer_) {
581 GLFrameBuffer *gl_framebuffer = static_cast<GLFrameBuffer *>(framebuffer_);
582 if (gl_framebuffer->context_get() == GLContext::get()) {
583 if (framebuffer_mip_ != mip) {
584 framebuffer_->attachment_set(this->attachment_type(0),
585 GPU_ATTACHMENT_TEXTURE_MIP(this, mip));
586 framebuffer_mip_ = mip;
587 }
588 return framebuffer_;
589 }
590
591 /* Textures can be shared between contexts but this helper framebuffer cannot. */
592 GPU_framebuffer_free(framebuffer_);
593 framebuffer_ = nullptr;
594 }
596 framebuffer_ = GPU_framebuffer_create(name_.c_str());
597 framebuffer_->attachment_set(this->attachment_type(0), GPU_ATTACHMENT_TEXTURE_MIP(this, mip));
598 framebuffer_mip_ = mip;
599 has_pixels_ = true;
600 return framebuffer_;
601}
602
604
605/* -------------------------------------------------------------------- */
608
610static inline GLenum to_gl(GPUSamplerExtendMode extend_mode)
611{
612 switch (extend_mode) {
614 return GL_CLAMP_TO_EDGE;
616 return GL_REPEAT;
618 return GL_MIRRORED_REPEAT;
620 return GL_CLAMP_TO_BORDER;
621 default:
623 return GL_CLAMP_TO_EDGE;
624 }
625}
626
627GLuint GLTexture::samplers_state_cache_[GPU_SAMPLER_EXTEND_MODES_COUNT]
630GLuint GLTexture::custom_samplers_state_cache_[GPU_SAMPLER_CUSTOM_TYPES_COUNT] = {};
631
633{
634 glGenSamplers(samplers_state_cache_count_, &samplers_state_cache_[0][0][0]);
635
636 float max_anisotropy = 1.0f;
638 glGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &max_anisotropy);
639 }
640
641 for (int extend_yz_i = 0; extend_yz_i < GPU_SAMPLER_EXTEND_MODES_COUNT; extend_yz_i++) {
642 const GPUSamplerExtendMode extend_yz = static_cast<GPUSamplerExtendMode>(extend_yz_i);
643 const GLenum extend_t = to_gl(extend_yz);
644
645 for (int extend_x_i = 0; extend_x_i < GPU_SAMPLER_EXTEND_MODES_COUNT; extend_x_i++) {
646 const GPUSamplerExtendMode extend_x = static_cast<GPUSamplerExtendMode>(extend_x_i);
647 const GLenum extend_s = to_gl(extend_x);
648
649 for (int filtering_i = 0; filtering_i < GPU_SAMPLER_FILTERING_TYPES_COUNT; filtering_i++) {
650 const GPUSamplerFiltering filtering = GPUSamplerFiltering(filtering_i);
651
652 const GLenum mag_filter = (filtering & GPU_SAMPLER_FILTERING_LINEAR) ? GL_LINEAR :
653 GL_NEAREST;
654 const GLenum linear_min_filter = (filtering & GPU_SAMPLER_FILTERING_MIPMAP) ?
655 GL_LINEAR_MIPMAP_LINEAR :
656 GL_LINEAR;
657 const GLenum nearest_min_filter = (filtering & GPU_SAMPLER_FILTERING_MIPMAP) ?
658 GL_NEAREST_MIPMAP_LINEAR :
659 GL_NEAREST;
660 const GLenum min_filter = (filtering & GPU_SAMPLER_FILTERING_LINEAR) ? linear_min_filter :
661 nearest_min_filter;
662
663 GLuint sampler = samplers_state_cache_[extend_yz_i][extend_x_i][filtering_i];
664 glSamplerParameteri(sampler, GL_TEXTURE_WRAP_S, extend_s);
665 glSamplerParameteri(sampler, GL_TEXTURE_WRAP_T, extend_t);
666 glSamplerParameteri(sampler, GL_TEXTURE_WRAP_R, extend_t);
667 glSamplerParameteri(sampler, GL_TEXTURE_MIN_FILTER, min_filter);
668 glSamplerParameteri(sampler, GL_TEXTURE_MAG_FILTER, mag_filter);
669
671 (filtering & GPU_SAMPLER_FILTERING_MIPMAP) &&
672 (filtering & GPU_SAMPLER_FILTERING_ANISOTROPIC_MASK))
673 {
674 glSamplerParameterf(
675 sampler,
676 GL_TEXTURE_MAX_ANISOTROPY_EXT,
677 min_ff(float(GPU_anisotropic_samples_get(filtering)), max_anisotropy));
678 }
679
680 /* Other states are left to default:
681 * - GL_TEXTURE_BORDER_COLOR is {0, 0, 0, 0}.
682 * - GL_TEXTURE_MIN_LOD is -1000.
683 * - GL_TEXTURE_MAX_LOD is 1000.
684 * - GL_TEXTURE_LOD_BIAS is 0.0f.
685 */
686
687 const GPUSamplerState sampler_state = {filtering, extend_x, extend_yz};
688 const std::string sampler_name = sampler_state.to_string();
689 debug::object_label(GL_SAMPLER, sampler, sampler_name.c_str());
690 }
691 }
692 }
693
694 glGenSamplers(GPU_SAMPLER_CUSTOM_TYPES_COUNT, custom_samplers_state_cache_);
695
696 /* Compare sampler for depth textures. */
697 GLuint compare_sampler = custom_samplers_state_cache_[GPU_SAMPLER_CUSTOM_COMPARE];
698 glSamplerParameteri(compare_sampler, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
699 glSamplerParameteri(compare_sampler, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
700 glSamplerParameteri(compare_sampler, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
701 glSamplerParameteri(compare_sampler, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
702 glSamplerParameteri(compare_sampler, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
703 glSamplerParameteri(compare_sampler, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_REF_TO_TEXTURE);
704 glSamplerParameteri(compare_sampler, GL_TEXTURE_COMPARE_FUNC, GL_LEQUAL);
705
706 debug::object_label(GL_SAMPLER, compare_sampler, "compare");
707
708 /* Custom sampler for icons. The icon texture is sampled within the shader using a -0.5f LOD
709 * bias. */
710 GLuint icon_sampler = custom_samplers_state_cache_[GPU_SAMPLER_CUSTOM_ICON];
711 glSamplerParameteri(icon_sampler, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST);
712 glSamplerParameteri(icon_sampler, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
713
714 debug::object_label(GL_SAMPLER, icon_sampler, "icons");
715}
716
718{
719 glDeleteSamplers(samplers_state_cache_count_, &samplers_state_cache_[0][0][0]);
720 glDeleteSamplers(GPU_SAMPLER_CUSTOM_TYPES_COUNT, custom_samplers_state_cache_);
721}
722
724{
725 /* Internal sampler states are signal values and do not correspond to actual samplers. */
727
729 return custom_samplers_state_cache_[sampler_state.custom_type];
730 }
731
732 return samplers_state_cache_[sampler_state.extend_yz][sampler_state.extend_x]
734}
735
737
738/* -------------------------------------------------------------------- */
743
744bool GLTexture::proxy_check(int mip)
745{
746 /* NOTE: This only checks if this mipmap is valid / supported.
747 * TODO(fclem): make the check cover the whole mipmap chain. */
748
749 /* Manual validation first, since some implementation have issues with proxy creation. */
750 int max_size = GPU_max_texture_size();
751 int max_3d_size = GPU_max_texture_3d_size();
752 int max_cube_size = GLContext::max_cubemap_size;
753 int size[3] = {1, 1, 1};
754 this->mip_size_get(mip, size);
755
756 if (type_ & GPU_TEXTURE_ARRAY) {
757 if (this->layer_count() > GPU_max_texture_layers()) {
758 return false;
759 }
760 }
761
762 if (type_ == GPU_TEXTURE_3D) {
763 if (size[0] > max_3d_size || size[1] > max_3d_size || size[2] > max_3d_size) {
764 return false;
765 }
766 }
767 else if ((type_ & ~GPU_TEXTURE_ARRAY) == GPU_TEXTURE_2D) {
768 if (size[0] > max_size || size[1] > max_size) {
769 return false;
770 }
771 }
772 else if ((type_ & ~GPU_TEXTURE_ARRAY) == GPU_TEXTURE_1D) {
773 if (size[0] > max_size) {
774 return false;
775 }
776 }
777 else if ((type_ & ~GPU_TEXTURE_ARRAY) == GPU_TEXTURE_CUBE) {
778 if (size[0] > max_cube_size) {
779 return false;
780 }
781 }
782
785 {
786 /* Some AMD drivers have a faulty `GL_PROXY_TEXTURE_..` check.
787 * (see #55888, #56185, #59351).
788 * Checking with `GL_PROXY_TEXTURE_..` doesn't prevent `Out Of Memory` issue,
789 * it just states that the OGL implementation can support the texture.
790 * So we already manually check the maximum size and maximum number of layers.
791 * Same thing happens on Nvidia/macOS 10.15 (#78175). */
792 return true;
793 }
794
795 GLenum gl_proxy = to_gl_proxy(type_);
796 GLenum internal_format = to_gl_internal_format(format_);
797 GLenum gl_format = to_gl_data_format(format_);
798 GLenum gl_type = to_gl(to_texture_data_format(format_));
799 /* Small exception. */
800 int dimensions = (type_ == GPU_TEXTURE_CUBE) ? 2 : this->dimensions_count();
801
803 size_t img_size = ((size[0] + 3) / 4) * ((size[1] + 3) / 4) * to_block_size(format_);
804 switch (dimensions) {
805 default:
806 case 1:
807 glCompressedTexImage1D(gl_proxy, mip, size[0], 0, gl_format, img_size, nullptr);
808 break;
809 case 2:
810 glCompressedTexImage2D(gl_proxy, mip, UNPACK2(size), 0, gl_format, img_size, nullptr);
811 break;
812 case 3:
813 glCompressedTexImage3D(gl_proxy, mip, UNPACK3(size), 0, gl_format, img_size, nullptr);
814 break;
815 }
816 }
817 else {
818 switch (dimensions) {
819 default:
820 case 1:
821 glTexImage1D(gl_proxy, mip, internal_format, size[0], 0, gl_format, gl_type, nullptr);
822 break;
823 case 2:
824 glTexImage2D(
825 gl_proxy, mip, internal_format, UNPACK2(size), 0, gl_format, gl_type, nullptr);
826 break;
827 case 3:
828 glTexImage3D(
829 gl_proxy, mip, internal_format, UNPACK3(size), 0, gl_format, gl_type, nullptr);
830 break;
831 }
832 }
833
834 int width = 0;
835 glGetTexLevelParameteriv(gl_proxy, 0, GL_TEXTURE_WIDTH, &width);
836 return (width > 0);
837}
838
840
842{
843 /* Do not check if using compute shader. */
844 GLShader *sh = dynamic_cast<GLShader *>(Context::get()->shader);
845 if (sh && sh->is_compute()) {
846 return;
847 }
849 std::optional<GPUAttachmentType> type = fb_attachments_.lookup_try(fb);
850 if (type.has_value()) {
851 GPUAttachment attachment = fb->attachments_[*type];
852 /* Check for when texture is used with texture barrier. */
853 GPUAttachment attachment_read = fb->tmp_detached_[*type];
854 if (attachment.mip <= mip_max_ && attachment.mip >= mip_min_ && attachment_read.tex == nullptr)
855 {
856 char msg[256];
857 SNPRINTF(msg,
858 "Feedback loop: Trying to bind a texture (%s) with mip range %d-%d but mip %d is "
859 "attached to the active framebuffer (%s)",
860 name_.c_str(),
861 mip_min_,
862 mip_max_,
863 attachment.mip,
864 fb->name_);
866 }
867 }
868}
869
870/* -------------------------------------------------------------------- */
873
875{
876 glGenBuffers(1, &gl_id_);
877 BLI_assert(gl_id_);
878
879 if (!gl_id_) {
880 return;
881 }
882
883 /* Ensure size is non-zero for pixel buffer backing storage creation. */
884 size = max_ii(size, 32);
885
886 glBindBuffer(GL_PIXEL_UNPACK_BUFFER, gl_id_);
887 glBufferData(GL_PIXEL_UNPACK_BUFFER, size, nullptr, GL_DYNAMIC_DRAW);
888 glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);
889}
890
892{
893 if (!gl_id_) {
894 return;
895 }
896 glDeleteBuffers(1, &gl_id_);
897}
898
900{
901 if (!gl_id_) {
902 BLI_assert(false);
903 return nullptr;
904 }
905
906 glBindBuffer(GL_PIXEL_UNPACK_BUFFER, gl_id_);
907 void *ptr = glMapBuffer(GL_PIXEL_UNPACK_BUFFER, GL_WRITE_ONLY);
908 BLI_assert(ptr);
909 return ptr;
910}
911
913{
914 glUnmapBuffer(GL_PIXEL_UNPACK_BUFFER);
915 glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);
916}
917
919{
920 GPUPixelBufferNativeHandle native_handle;
921 native_handle.handle = int64_t(gl_id_);
922 native_handle.size = size_;
923 return native_handle;
924}
925
927{
928 return size_;
929}
930
932} // namespace blender::gpu
#define SNPRINTF(dst, format,...)
#define GPU_ATTACHMENT_TEXTURE_MIP(_texture, _mip)
#define GPU_SAMPLER_CUSTOM_TYPES_COUNT
#define GPU_SAMPLER_EXTEND_MODES_COUNT
Read Blender memory allocation and freeing.
#define UNPACK2(a)
#define BLI_assert_unreachable()
#define BLI_assert(a)
#define UNPACK3(a)
#define ELEM(...)
#define BLI_assert_msg(a, msg)
btScalar max
constexpr int64_t size() const
constexpr IndexRange()=default
constexpr MutableSpan slice(const int64_t start, const int64_t size) const
Definition BLI_span.hh:579
constexpr T * data() const
Definition BLI_span.hh:545
constexpr Span slice(int64_t start, int64_t size) const
Definition BLI_span.hh:141
constexpr const T * data() const
Definition BLI_span.hh:219
static Context * get()
static bool stencil_texturing_support
Definition gl_context.hh:72
static GLStateManager * state_manager_active_get()
static void texture_free(GLuint tex_id)
static bool direct_state_access_support
Definition gl_context.hh:60
static GLContext * get()
static bool texture_filter_anisotropic_support
Definition gl_context.hh:74
static GLint max_cubemap_size
Definition gl_context.hh:53
GPUPixelBufferNativeHandle get_native_handle() override
size_t get_size() override
bool is_compute() const
Definition gl_shader.hh:170
void texture_bind_temp(GLTexture *tex)
Definition gl_state.cc:466
GLTexture(const char *name)
Definition gl_texture.cc:37
void update_sub(int mip, int offset[3], int extent[3], eGPUDataFormat type, const void *data, const uint unpack_row_length=0) override
friend class GLFrameBuffer
Definition gl_texture.hh:23
void read(int mip, eGPUDataFormat type, void *data) override
static void samplers_init()
static GLuint get_sampler(const GPUSamplerState &sampler_state)
void clear(const double4 data) override
static void samplers_free()
bool init_internal() override
Definition gl_texture.cc:58
void copy_to(Texture *dst, IndexRange mip_levels) override
void generate_mipmap() override
void swizzle_set(const char swizzle_mask[4]) override
virtual void texture_unbind(Texture *tex)=0
virtual void image_unbind(Texture *tex)=0
size_t read_size_get(int mip, eGPUDataFormat format) const
GPUAttachmentType attachment_type(int slot) const
Map< FrameBuffer *, GPUAttachmentType > fb_attachments_
void mip_size_get(int mip, int r_size[3]) const
TextureFormat format_get() const
Texture(const char *name)
GPUTextureFormatFlag format_flag_
#define sampler(slot)
int size(const AssetLibraryReference *library_reference)
void raise_gl_error(const char *info)
Definition gl_debug.cc:278
void object_label(GLenum type, GLuint object, const char *name)
Definition gl_debug.cc:331
static GLenum to_gl(GPUSamplerExtendMode extend_mode)
GLenum to_gl_internal_format(TextureFormat format)
GLenum to_gl_target(GPUTextureType type)
bool is_half_float(TextureFormat format)
eGPUDataFormat to_texture_data_format(TextureFormat tex_format)
GLenum to_gl_data_format(TextureFormat format)
GLenum to_gl_proxy(GPUTextureType type)
bool is_half_integer(TextureFormat format)
size_t to_block_size(TextureFormat data_type)
int to_bytesize(const DataFormat format)
GLenum swizzle_to_gl(const char swizzle)
int to_component_len(TextureFormat format)
constexpr bool validate_data_format(TextureFormat tex_format, eGPUDataFormat data_format)
GLenum to_gl(eGPUDataFormat format)
void float_to_half_make_finite_array(const float *src, uint16_t *dst, size_t length)
Definition math_half.cc:355
void parallel_for(const IndexRange range, const int64_t grain_size, const Function &function, const TaskSizeHints &size_hints=detail::TaskSizeHints_Static(1))
Definition BLI_task.hh:69
MINLINE float min_ff(float a, float b)
void GPU_framebuffer_bind(gpu::FrameBuffer *fb)
BLI_assert(slot->slot_subtype.map==BMO_OP_SLOT_SUBTYPE_MAP_FLT)
gpu::FrameBuffer * GPU_framebuffer_active_get()
__int64 int64_t
Definition BKE_text.h:90
unsigned int uint
Definition BKE_text.h:55
void GPU_framebuffer_free(gpu::FrameBuffer *fb)
BLI_INLINE float fb(float length, float L)
@ GPU_DATA_HALF_FLOAT
@ GPU_SAMPLER_EXTEND_MODE_MIRRORED_REPEAT
@ GPU_SAMPLER_EXTEND_MODE_CLAMP_TO_BORDER
@ GPU_SAMPLER_EXTEND_MODE_REPEAT
@ GPU_SAMPLER_EXTEND_MODE_EXTEND
@ GPU_SAMPLER_FILTERING_LINEAR
@ GPU_SAMPLER_FILTERING_MIPMAP
MINLINE int max_ii(int a, int b)
@ GPU_DRIVER_OFFICIAL
int GPU_max_texture_size()
unsigned short uint16_t
Definition BKE_text.h:80
void * MEM_new_uninitialized_aligned(size_t len, size_t alignment, const char *str) ATTR_WARN_UNUSED_RESULT ATTR_ALLOC_SIZE(1) ATTR_NONNULL(3)
bool GPU_type_matches(GPUDeviceType device, GPUOSType os, GPUDriverType driver)
VecBase< int32_t, 3 > int3
BMesh const char void * data
static const int GPU_SAMPLER_FILTERING_TYPES_COUNT
unsigned char uint8_t
Definition BKE_text.h:79
int GPU_max_texture_layers()
gpu::FrameBuffer * GPU_framebuffer_create(const char *name)
@ GPU_SAMPLER_CUSTOM_ICON
@ GPU_SAMPLER_CUSTOM_COMPARE
@ GPU_SAMPLER_STATE_TYPE_CUSTOM
@ GPU_SAMPLER_STATE_TYPE_INTERNAL
signed int int32_t
Definition BKE_text.h:78
int GPU_max_texture_3d_size()
VecBase< double, 4 > double4
signed short int16_t
Definition BKE_text.h:77
GPUPixelBufferNativeHandle GPU_pixel_buffer_get_native_handle(GPUPixelBuffer *pixel_buf)
#define min(a, b)
Definition sort.cc:38
GPUSamplerStateType type
GPUSamplerExtendMode extend_yz
GPUSamplerFiltering filtering
GPUSamplerCustomType custom_type
std::string to_string() const
GPUSamplerExtendMode extend_x