Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass texture with float values to shader

Tags:

c++

qt

opengl

glsl

qml

I am developing an application in C++ in QT QML 3D. I need to pass tens of float values (or vectors of float numbers) to fragment shader. These values are positions and colors of lights, so I need values more then range from 0.0 to 1.0. However, there is no support to pass an array of floats or integers to a shader in QML. My idea is to save floats to a texture, pass the texture to a shader and get the values from that.

I tried something like this:

float array [4] = {100.5, 60.05, 63.013, 0.0};
uchar data [sizeof array * sizeof(float)];
memcpy(data, &array, sizeof array * sizeof(float));
QImage img(data, 4, 1, QImage::Format_ARGB32);

and pass this QImage to a fragment shader as sampler2D. But is there there a method like memcpy to get values from texture in GLSL? texelFetch method only returns me vec4 with float numbers range 0.0 to 1.0. So how can I get the original value from the texture in a shader? I prefer to use sampler2D type, however, is there any other type supporting direct memory access in GLSL?

like image 602
david Avatar asked Jan 22 '26 03:01

david


2 Answers

This will create a float texture from a float array.

glTexImage2D(GL_TEXTURE_2D, 0, GL_R32F, width, height, 0, GL_RED, GL_FLOAT, &array);

You can access float values from your fragment shader like this:

uniform sampler2D float_texture;

...

float float_texel = float( texture2D(float_texture, tex_coords.xy) );

"OpenGL float texture" is a well documented subject. What exactly is a floating point texture?

like image 169
Octo Avatar answered Jan 23 '26 17:01

Octo


The texture accessing functions do directly read from the texture. The problem is that Format_ARGB32 is not 32-bits per channel; it's 32-bits per pixel. From this documentation page, it seems clear that QImage cannot create floating-point images; it only deals in normalized formats. QImage itself seems to be a class intended for dealing with GUI matters, not for loading OpenGL images.

You'll have to ditch Qt image shortcuts and actually use OpenGL directly.

like image 44
Nicol Bolas Avatar answered Jan 23 '26 15:01

Nicol Bolas