为什么这个着色器圆比传递的半径小很多?
Why is this shader circle so much smaller than the passed radius?
我正在开发一个 GLSL 着色器,它根据给定的中心位置和半径绘制一个圆。出于某种我不明白的原因,圆的半径与我传递的不匹配。也就是说,当我为 u_radius
传入 100
时,半径改为 56
。我尝试将着色器中的值加倍,虽然接近,但仍然有点不准确。有谁知道可能导致差异的原因吗?
precision mediump float;
varying vec4 v_pos;
uniform mat3 u_matrix;
uniform vec2 u_center; // the center of the circle in world coordinates
uniform float u_aspect; // aspect ratio. 1.7778 for my monitor (1920x1080)
uniform float u_radius; // radius. passing in 100
uniform vec2 u_canvasSize; // [ 1920, 1080 ]
void main() {
vec4 c = vec4((u_matrix * vec3(u_center, 1)).xy, 0, 1); // center
vec2 onePix = vec2(1.0, 1.0) / u_canvasSize; // the size of one pixel in clip-space
float onePixLength = sqrt(onePix.x * onePix.x + onePix.y * onePix.y); // magnitude of one pixel
float r = onePixLength * u_radius; // radius converted to clip-space
vec2 dist = (v_pos.xy - c.xy) * vec2(u_aspect, 1.0); // distance from center to current shader point
if (dist.x * dist.x + dist.y * dist.y > r * r) {
discard;
}
gl_FragColor = vec4(1.0, 1.0, 1.0, 1.0);
}
这是因为归一化设备 space 坐标在 [-1.0, 1.0] 范围内。因此在计算像素大小时缺少了一个因子 2:
vec2 onePix = vec2(1.0, 1.0) / u_canvasSize;
vec2 onePix = vec2(2.0) / u_canvasSize;
此外,您需要计算像素的边长而不是对角线长度。宽度(x 维度)按纵横比缩放。因此,需要计算一个像素的高度:
float onePixLength = sqrt(onePix.x * onePix.x + onePix.y * onePix.y);
float onePixLength = onePix.y;
注意,onePix.x * u_aspect
等于 onePix.y
。
我正在开发一个 GLSL 着色器,它根据给定的中心位置和半径绘制一个圆。出于某种我不明白的原因,圆的半径与我传递的不匹配。也就是说,当我为 u_radius
传入 100
时,半径改为 56
。我尝试将着色器中的值加倍,虽然接近,但仍然有点不准确。有谁知道可能导致差异的原因吗?
precision mediump float;
varying vec4 v_pos;
uniform mat3 u_matrix;
uniform vec2 u_center; // the center of the circle in world coordinates
uniform float u_aspect; // aspect ratio. 1.7778 for my monitor (1920x1080)
uniform float u_radius; // radius. passing in 100
uniform vec2 u_canvasSize; // [ 1920, 1080 ]
void main() {
vec4 c = vec4((u_matrix * vec3(u_center, 1)).xy, 0, 1); // center
vec2 onePix = vec2(1.0, 1.0) / u_canvasSize; // the size of one pixel in clip-space
float onePixLength = sqrt(onePix.x * onePix.x + onePix.y * onePix.y); // magnitude of one pixel
float r = onePixLength * u_radius; // radius converted to clip-space
vec2 dist = (v_pos.xy - c.xy) * vec2(u_aspect, 1.0); // distance from center to current shader point
if (dist.x * dist.x + dist.y * dist.y > r * r) {
discard;
}
gl_FragColor = vec4(1.0, 1.0, 1.0, 1.0);
}
这是因为归一化设备 space 坐标在 [-1.0, 1.0] 范围内。因此在计算像素大小时缺少了一个因子 2:
vec2 onePix = vec2(1.0, 1.0) / u_canvasSize;
vec2 onePix = vec2(2.0) / u_canvasSize;
此外,您需要计算像素的边长而不是对角线长度。宽度(x 维度)按纵横比缩放。因此,需要计算一个像素的高度:
float onePixLength = sqrt(onePix.x * onePix.x + onePix.y * onePix.y);
float onePixLength = onePix.y;
注意,onePix.x * u_aspect
等于 onePix.y
。