Skip to content

Commit

Permalink
Add getModelViewPosition function
Browse files Browse the repository at this point in the history
  • Loading branch information
vanruesc committed Mar 30, 2024
1 parent 4625ee0 commit 149a231
Showing 1 changed file with 19 additions and 4 deletions.
23 changes: 19 additions & 4 deletions src/shader-chunks/shaders/depth-utils-pars.frag
Original file line number Diff line number Diff line change
Expand Up @@ -43,23 +43,38 @@ float readDepth(sampler2D depthBuffer, const in vec2 uv, const in float near, co
* @param depth - The depth value.
* @param viewZ - The viewZ value.
* @param projectionMatrix - The projection matrix.
* @param inverseProjectionMatrix - The inverse projection matrix.
* @param projectionMatrixInverse - The inverse projection matrix.
* @return The view position.
*/

vec3 getViewPosition(const in vec2 screenPosition, const in float depth, const in float viewZ,
const in mat4 projectionMatrix, const in mat4 inverseProjectionMatrix) {
const in mat4 projectionMatrix, const in mat4 projectionMatrixInverse) {

vec4 clipPosition = vec4(vec3(screenPosition, depth) * 2.0 - 1.0, 1.0);

// Unoptimized version:
// vec4 viewPosition = inverseProjectionMatrix * clipPosition;
// vec4 viewPosition = projectionMatrixInverse * clipPosition;
// viewPosition /= viewPosition.w; // Unproject.
// return viewPosition.xyz;

float clipW = projectionMatrix[2][3] * viewZ + projectionMatrix[3][3];
clipPosition *= clipW; // Unproject.

return (inverseProjectionMatrix * clipPosition).xyz;
return (projectionMatrixInverse * clipPosition).xyz;

}

/**
* Calculates the model view position based on a given view position and view matrix.
*
* @param viewPosition - The view position.
* @param viewMatrix - The inverse camera transformation matrix.
* @return The model view position.
*/

vec3 getModelViewPosition(const in vec3 viewPosition, const in mat4 viewMatrix) {

vec4 mvPosition = viewMatrix * vec4(viewPosition, 1.0);
return -mvPosition.xyz;

}

0 comments on commit 149a231

Please sign in to comment.