three.js - GLSL Fragment shader 基于世界空间的UV置换
问题描述
我正在尝试为网站上的图像创建 rgb 偏移效果。我有基本的功能,但问题是通道与纹理的 uv 偏移。因此,如果图像大小不同,则每个图像的偏移量在视觉上是不同的。
这是我的片段着色器。
uniform sampler2D texture;
varying vec2 vUv; // vertex uv
void main() {
vec2 uv = vUv;
float red = texture2D(texture, vec2(uv.x, uv.y - .1)).r;
float green = texture2D(texture, uv).g;
float blue = texture2D(texture, vec2(uv.x, uv.y + .1)).b;
float alpha = texture2D(texture, uv).a;
gl_FragColor = vec4(vec3(red, green, blue), alpha);
}
以及它在页面上的呈现方式。
我将如何在不必传入统一值的情况下标准化 uv 偏移量?
解决方案
传递更多信息(如偏移量)是正常的
uniform float offset1;
uniform float offset2;
uniform sampler2D texture;
varying vec2 vUv; // vertex uv
void main() {
vec2 uv = vUv;
float red = texture2D(texture, vec2(uv.x, uv.y + offset1)).r;
float green = texture2D(texture, uv).g;
float blue = texture2D(texture, vec2(uv.x, uv.y + offset2)).b;
float alpha = texture2D(texture, uv).a;
gl_FragColor = vec4(vec3(red, green, blue), alpha);
}
然后,您可以在 JavaScript 中进行调整。例如
const uniforms = {
offset1: { value: 0 },
offset2: { value: 0 },
...
};
...
uniforms.offset1.value = 2 / textureHeight;
uniforms.offset2.value = -2 / textureHeight;
如果是我,我可能会这样做
uniform vec2 channelOffsets[4];
uniform vec4 channelMult[4];
uniform sampler2D texture;
varying vec2 vUv; // vertex uv
void main() {
vec2 uv = vUv;
vec4 channel0 = texture2D(texture, uv + channelOffset[0]);
vec4 channel1 = texture2D(texture, uv + channelOffset[1]);
vec4 channel2 = texture2D(texture, uv + channelOffset[2]);
vec4 channel3 = texture2D(texture, uv + channelOffset[3]);
gl_FragColor =
channelMult[0] * channel0 +
channelMult[1] * channel1 +
channelMult[2] * channel2 +
channelMult[3] * channel3 ;
}
并设置它们
const uniforms = {
channelOffsets: { value: [
new THREE.Vector2(),
new THREE.Vector2(),
new THREE.Vector2(),
new THREE.Vector2(),
]},
channelMults: { value: [
new THREE.Vector4(1, 0, 0, 0),
new THREE.Vector4(0, 1, 0, 0),
new THREE.Vector4(0, 0, 1, 0),
new THREE.Vector4(0, 0, 0, 1),
]},
....
}
...
uniforms.channelOffsets.value[0].y = -2 / textureHeight;
uniforms.channelOffsets.value[2].y = 2 / textureHeight;
举一个不那么硬编码的例子。我什至可以使用纹理矩阵而不是偏移量,这将允许旋转和缩放每个通道,并将它们与允许交换通道的矩阵组合。
推荐阅读
- vb.net - DataGridView 实时搜索数据
- c++ - static_cast vs reinterpret_cast,细微的差异?
- javascript - 侦听来自另一个文件的模态关闭事件
- python - 遍历字典列表的大 O 时间复杂度
- wso2-am - WSO2 api 管理器 SSLPeerUnverifiedException:对等体未通过身份验证
- android - 如何在 Jetpack Compose 中的现有 LazyColumn 之上添加 CircularProgressIndicator?
- database - 将烧瓶 Web 应用程序连接到 vm 中的数据库
- multithreading - 使用 Kotlin 中不同线程的结果更新列表
- vue.js - Ionic Vue 和 AR.js
- c# - AWS 弹性 beanstalk Linux 的 .NET 中的 .ebextensions 文件夹在哪里