如何有效地用零初始化纹理? [英] How to efficiently initialize texture with zeroes?

查看:152
本文介绍了如何有效地用零初始化纹理?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要用零初始化 OpenGL 2D 纹理.

I need to initialize an OpenGL 2D texture with zeroes.

为什么?我用 OpenCL 渲染到这个纹理.粗略地说,渲染阶段是:

Why? I render to this texture with OpenCL. Roughly, rendering stages are:

  1. 创建 RGBA 纹理,初始化为零(因此它包含透明的黑色像素)
  2. OpenCL:计算某些对象可见的像素的颜色并将它们写入此纹理
  3. OpenGL:将环境映射添加到透明像素并显示最终图像

因此我不需要将任何实际的纹理数据传递给 glTexImage2d.但是根据规范,当我传递 data=NULL 时,纹理内存已分配但未初始化.

I therefore do not need to pass any actual texture data to glTexImage2d. But according to the spec, when I pass data=NULL, the texture memory is allocated but not initialized.

分配一个用零填充的客户端内存并传递给 glTexImage2D 不是一个很好的选择,尽管我只能想到一个.

Allocating a client-side memory filled with zeroes and passing to glTexImage2D is not a very good option although only one I can think of.

我实际上只想初始化 alpha 组件(无论如何 RGB 都会被覆盖),但我怀疑这会使情况变得更容易.

I actually want to init only alpha component (RGB will get overriden anyway), but I doubt this make the situation any easier.

推荐答案

有几种方法可以做到这一点:

There are several ways to do this:

1:给定纹理的宽度和高度:

1: Given a width and a height for a texture:

std::vector<GLubyte> emptyData(width * height * 4, 0);
glBindTexture(GL_TEXTURE_2D, texture);
glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, width, height, GL_BGRA, GL_UNSIGNED_BYTE, &emptyData[0]);

为了获得最大效率,您应该在调用它和 OpenCL 开始工作之间留出一些时间.

For maximum efficiency, you should leave some time between when you call this and when OpenCL starts its work.

2:将其附加到 FBO 并使用 glClearBuffer.

2: Attach it to an FBO and use glClearBuffer.

glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo);
glFramebufferTexture(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, texture, 0); //Only need to do this once.
glDrawBuffer(GL_COLOR_ATTACHMENT0); //Only need to do this once.
GLuint clearColor[4] = {0, 0, 0, 0};
glClearBufferuiv(GL_COLOR, 0, clearColor);

这似乎应该更快,因为没有 CPU-GPU DMA 正在进行.但 FBO 的绑定和解除绑定可能会导致效率低下.再说一次,它可能不会.对其进行配置以确保.

This seems like it should be faster, since there is no CPU-GPU DMA going on. But the binding and unbinding of FBOs may introduce inefficiencies. Then again, it may not. Profile it to make sure.

请注意,这仅适用于可用作渲染目标的图像格式.所以不是压缩纹理.

Note that this only works for image formats that can be used as render targets. So not compressed textures.

3:如果有足够的驱动程序,您可以使用新的 ARB_clear_texture扩展名:

3: Given sufficient drivers, you can use the new ARB_clear_texture extension:

glClearTexImage(texture, 0, GL_BGRA, GL_UNSIGNED_BYTE, &clearColor);

请注意,这仅适用于可以通过标准像素传输提供数据的图像格式.所以不是压缩格式.

Note that this only works for image formats whose data can be provided by standard pixel transfers. So not compressed formats.

这篇关于如何有效地用零初始化纹理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆