How can I color things in OpenGL ES 2.0 based on their depth?

I am writing an OpenGL ES 2.0 game (for iOS). How can I create a shader (since I assume that it will be easier to do in the shader) so that the geometry farther from the origin (along the Z axis) appears darker?

The water in this image illustrates the effect that I mean.

Zarch
(source: bytecellar.com )

+6
source share
2 answers

This is pretty easy to do if you just want to use the Z position of your geometry. You can have a vertex shader as shown below:

attribute vec4 position; varying float zDepth; uniform mat4 modelViewProjMatrix; void main() { vec4 newPosition = modelViewProjMatrix * position; gl_Position = newPosition; zDepth = (2.0 - (1.0 + newPosition.z))/2.0; } 

and fragment shader for example

 varying highp float zDepth; void main() { gl_FragColor = vec4(zDepth, zDepth, 0.0, 1.0); } 

which will look like this:

Depth-shaded OpenGL teapot

I have an example of this in this sample code for iPad I have compiled for my class OpenGL ES 2.0.

+8
source

I did a pretty interesting test with what @brad provides. I just change the line:

 gl_FragColor = vec4(1.0, 1.0, 0.0, zDepth); 

Nothing happens with alpha. Is it me or is there something else missing, as for Alpha ?

0
source

Source: https://habr.com/ru/post/908932/


All Articles