You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

着色器中UV重映射与宽高比修正代码的单行化简方法

GLSL UV坐标代码化简逻辑解释

先看原始的三行GLSL代码:

vec2 uv = fragCoord/iResolution.xy; // <0, 1>
uv -= 0.5; // <-0.5,0.5>
uv.x *= iResolution.x/iResolution.y; // fix aspect ratio

目标是化简为单行代码:

vec2 uv = (fragCoord - .5 * iResolution.xy) / iResolution.y; // Condense 3 lines down to a single line!

我们可以通过拆分x、y分量分别推导化简过程:

1. 推导x分量的化简

原始三行对x分量的运算步骤:

  1. 初始赋值:uv.x = fragCoord.x / iResolution.x
  2. 偏移中心:uv.x = (fragCoord.x / iResolution.x) - 0.5
  3. 修正宽高比:uv.x = [(fragCoord.x / iResolution.x) - 0.5] * (iResolution.x / iResolution.y)

对第三步的表达式展开并化简:

uv.x = (fragCoord.x / iResolution.x) * (iResolution.x / iResolution.y) - 0.5 * (iResolution.x / iResolution.y)
// 第一项中iResolution.x可以约去
= fragCoord.x / iResolution.y - (0.5 * iResolution.x) / iResolution.y
// 合并分母
= (fragCoord.x - 0.5 * iResolution.x) / iResolution.y

2. 推导y分量的化简

原始三行对y分量的运算步骤:

  1. 初始赋值:uv.y = fragCoord.y / iResolution.y
  2. 偏移中心:uv.y = (fragCoord.y / iResolution.y) - 0.5
  3. y分量无额外宽高比修正,保持上一步结果

将第二步的表达式整理为统一分母形式:

uv.y = (fragCoord.y / iResolution.y) - 0.5
// 把0.5转化为以iResolution.y为分母的形式
= (fragCoord.y / iResolution.y) - (0.5 * iResolution.y) / iResolution.y
// 合并分母
= (fragCoord.y - 0.5 * iResolution.y) / iResolution.y

3. 合并为向量表达式

GLSL支持向量的整体运算,我们可以把x、y分量的化简结果合并:

  • fragCoord.x - 0.5*iResolution.x 和 fragCoord.y - 0.5*iResolution.y 可以写成向量形式 fragCoord - 0.5*iResolution.xy
  • 两个分量都除以iResolution.y,等价于向量整体除以这个标量

最终就得到了单行的化简代码:

vec2 uv = (fragCoord - .5 * iResolution.xy) / iResolution.y;

内容的提问来源于stack exchange,提问作者Artyom Chernyaev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 11:20:12