Dahl
Dahl

Reputation: 176

Sampling from texture in fragment shader with UV's proportional to perspective

In the fragment shader:

If I have a texture (the size of viewport) uploaded as a uniform sampler2D. The texture was rendered to in a earlier pass. The currently running fragment corresponds 1:1 to the texture in UV space. The fragment shader samples surrounding pixels in the texture based on a delta value.

How can I keep delta proportional to the camera perspective?

For instance: delta is 1 unit in world space.

If it helps, you can assume:

Camera has orthographic projection.

You have access to the fragments' world position.

viewport / texture - resolution: (1280, 720)

Edit

Here is what I think I could do:

Every frame on the CPU (or when the camera projection changes):

(sudo code)

Mat4 combined = camera.projection() * camera.view();

Vec4 world_delta = Vec4(1,1,0,0); // Not a position

Vec2 ndc_delta = (combined * world_delta).xy;

Vec2 uv_delta = ndc_delta / 2;

shader.uploadUniform(uv_delta);

Upvotes: 0

Views: 559

Answers (1)

Dahl
Dahl

Reputation: 176

I was complicating the problem. Not understanding orthographic projection.

How can I keep delta proportional to the camera perspective?

A viewport [16,9] units and world_delta [1,1] units

width *= zoom;
height *= zoom;

right = width / 2;
left = -right
top = height / 2;
bottom = -top;

Then as BDL pointed out in the comments, you can derive the delta in NDC from:

ndc_delta.x = world_delta.x / (right - left);
ndc_delta.y = world_delta.y / (top - bottom);

or simply:

ndc_delta.x = world_delta.x / width;
ndc_delta.y = world_delta.y / height;

Upvotes: 0

Related Questions