UV Coordinates & Uniforms -- OpenGL UV坐标和Uniform变量

Task

A shader is a set of instructions that are executed simultaneously for each pixel on the screen. It can produce different color result depending on the pixel data such as position on the screen.
Use the x component of the pixel's normalized coordinates as the red and the y component as the green when writing pixel's color. As a result, you should notice that the intensity of the red color increases from left to right, and the intensity of the green color increases from bottom to top. In the upper right corner we get yellow color as a result of mixing green and red.
着色器是一组针对屏幕上每个像素同时执行的指令。它可以根据像素数据(例如屏幕上不同的位置)产生不同的颜色效果。
在写入像素颜色时,使用x像素标准化坐标的分量作为红色,使用y分量作为绿色。因此,你可以注意到红色的强度从左到右增加,而绿色的强度从下到上增加。在右上角,我们得到了黄色,这是绿色和红色混合的结果。

Theory

着色器程序用于创建 2D 图像或纹理。为了避免处理生成的纹理的具体尺寸,我们将使用UV坐标。这是纹理坐标的规范化,其中纹理的左下角为(0, 0),右上角为(1.0, 1.0)

规范化像素坐标

要获取当前像素的标准化坐标,请将其位置除以纹理的分辨率:

ini 复制代码
vec2 uv = gl_FragCoord.xy / iResolution.xy;

gl_FragCoord

gl_FragCoord是着色器程序中的一个内置变量,用于表示正在处理的片段的像素坐标。它是一个四维向量,包含片段位置的 X、Y、Z 和 W 分量:

  • X 和 Y:片段的屏幕空间坐标。
  • Z:深度值。
  • W:分别为透视除法值。

gl_FragCoord变量通常用于根据片段的位置执行各种计算。

iResolution

iResolution是一个用于保存纹理分辨率的Uniform变量。Uniform用于将CPU的一些输入发送到所有着色器程序。每个程序接收相同的数据,它们可以读取但无法更改。Uniform的目的是为应用程序提供一种方法来控制着色器的行为,而无需修改着色器代码本身。这使得渲染更加灵活,因为同一个着色器可以使用不同的数据输入来产生不同的效果。

Answer

glsl 复制代码
uniform vec2 iResolution;

void main() {
  vec2 uv = gl_FragCoord.xy / iResolution.xy;
  gl_FragColor = vec4(uv, 0.0, 1.0);
}

练习

UV Coordinates & Uniforms

相关推荐
LinXunFeng3 小时前
Obsidian - 使用 Share Note 分享笔记并自部署
前端·笔记·github
乘风gg7 小时前
为什么AI 时代来临,大部分人吃不到红利
前端·ai编程·claude
恋猫de小郭7 小时前
Android 限制侧载新进展,谷歌联合国内厂商推验证计划
android·前端·flutter
IT_陈寒7 小时前
Redis内存爆了,原来我漏掉了这个致命配置
前端·人工智能·后端
恋猫de小郭7 小时前
解读 Android 17 全新内存限制,有没有“豁免”后门?
android·前端·flutter
Hyyy9 小时前
理解LLM的基本工作原理:预训练、微调、推理的区别
前端
Gatlin9 小时前
前端逆向与反逆向:一场猫鼠游戏的底层逻辑与实战
前端
Pedantic9 小时前
本地通知(Local Notifications)学习笔记
前端
森蓝情丶10 小时前
我给 AI 搭了个法庭:一个前端仔的 LangGraph 实战全记录
前端·后端
爱勇宝10 小时前
干了近 8 年,一夜之间被裁:AI 时代,程序员最该害怕的不是 AI
前端·后端·程序员