Adam's Lair Forum
https://forum.adamslair.net:80/

How to get world space vertex position in shader?
https://forum.adamslair.net:80/viewtopic.php?f=4&t=923
Page 1 of 1

Author:  loeller [ 2016/09/04, 15:41 ]
Post subject:  How to get world space vertex position in shader?

Hello,
The title basically says it: I'd like to use the world space (or object space, doesn't really matter) position of vertices in my shader, which is rendering a tilemap. The default vertex shader has this line:
Code:
gl_Position = ftransform();

But it returns the screen space position of the vertex. Searched it with google, but didn't succeed to find anything useful.
Thanks in advance!

Author:  Adam [ 2016/09/04, 15:46 ]
Post subject:  Re: How to get world space vertex position in shader?

It's currently not possible to get the world space vertex position directly, mostly because the vertices that are passed to the backend are already transformed by the renderer on CPU side, using drawDevice.PreprocessCoords. This is one of the things that will change in v3.0.

Until then, you can reverse-engineer their world space position using builtin shader variables. The sample vertex shader from the basic shaders package does this step one of this, which is determining the scale. It also floats around the vertex a bit over time, ignore that part ^^

Edit: You'll also need the builtin CameraPosition field.

Author:  loeller [ 2016/09/04, 15:47 ]
Post subject:  Re: How to get world space vertex position in shader?

Okay, thank you for the quick reply ^^

Author:  loeller [ 2016/09/04, 16:58 ]
Post subject:  Re: How to get world space vertex position in shader?

Here's the vertex shader code if someone is interested:

Code:
vec3 reverse ()
{
   // Duality uses software pre-transformation of vertices
   // gl_Vertex is already in parallax (scaled) view space when arriving here.
   vec4 vertex = gl_Vertex;
   
   // Reverse-engineer the scale that was previously applied to the vertex
   float scale = 1.0;
   if (CameraParallax)
   {
      scale = CameraFocusDist / vertex.z;
   } else {
   // default focus dist is 500
      scale = CameraFocusDist / 500.0;
   }
   
   return vec3 (vertex.xyz + vec3 (CameraPosition.xy, 0)) / scale;
}

Author:  Adam [ 2016/09/04, 17:48 ]
Post subject:  Re: How to get world space vertex position in shader?

loeller wrote:
Here's the vertex shader code if someone is interested:

:+1:

Page 1 of 1 All times are UTC + 1 hour [ DST ]
Powered by phpBB® Forum Software © phpBB Group
http://www.phpbb.com/