Is there a way in a fragment shader that has a given sampler2D
to convert this to a samplerCube
? I want the Cube to have the sampler2D
texture on all six sides. The application cannot be changed to pass a samplerCube
to the shader, but I need one in my fragment shader.

- 4,973
- 4
- 36
- 81
-
"*I want the Cube to have the sampler2D texture on all six sides.*" What do you mean by that? A cubemap is a texture that has 6 2D-images per mipmap level. If you only have a single 2D image, where do the other 5 sides come from? – Nicol Bolas Dec 19 '19 at 14:23
-
all sides have the same texture. So this 1 texture can be used 6 times. – Nidhoegger Dec 19 '19 at 14:34
-
no you can't create vertices in a fragment shader. In the end it seems like you want the same as [the question](https://stackoverflow.com/questions/59406663/drawing-a-cube-for-each-vertex) that was asked a few hours befor yours. to make it short, use a Geomerty Shader or Instanced Rendering – nkazz Dec 20 '19 at 07:47
-
@Nidhoegger had some time/mood for this today so I added working conversion GLSL code to my answer ... and preview of result – Spektre Dec 21 '19 at 11:38
1 Answers
You can write your own function converting 3D cube map direction coordinate into 2D texture coordinate using vector math ...
this might help:
The function should do this:
normalize input direction
detect which side your direction is hitting
by doing dot product of the input direction with the direction pointing to each cubemap face center. The maximum will identify hit face
project the direction onto the hit face
and doing dot product with basis vectors of the face you get your 2D coordinates. Beware each face has its rotation ...
Then just use that for access sampler2D with 3D direction as texture coordinate something like this:
uniform sampler2D txr;
...
vec2 mycubemap(vec3 dir)
{
vec2 tex;
dir=normalize(dir);
...
return tex;
}
void main()
{
...
???=texture2D(txr,mycubemap(???));
...
}
When I put all together + some optimizations I got this:
vec2 mycubemap(vec3 t3)
{
vec2 t2;
t3=normalize(t3)/sqrt(2.0);
vec3 q3=abs(t3);
if ((q3.x>=q3.y)&&(q3.x>=q3.z))
{
t2.x=0.5-t3.z/t3.x;
t2.y=0.5-t3.y/q3.x;
}
else if ((q3.y>=q3.x)&&(q3.y>=q3.z))
{
t2.x=0.5+t3.x/q3.y;
t2.y=0.5+t3.z/t3.y;
}
else{
t2.x=0.5+t3.x/t3.z;
t2.y=0.5-t3.y/q3.z;
}
return t2;
}
Using it with the layout rendering from the linked QA I got this output:
Using this as texture instead of cubemap:
Note the lines in square boundaries so there might be some additional edge case handling needed but too lazy to analyze further ...