GLSL着色器:在两个以上纹理之间插值 [英] GLSL shader: Interpolate between more than two textures

查看:729
本文介绍了GLSL着色器:在两个以上纹理之间插值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在OpenGL中实现了一个高度图。现在它只是一个正弦/余弦弯曲的地形。
目前我正在白色冰和深色石头纹理之间进行插值。
这样做:

I've implemented a heightmap in OpenGL. For now it is just a sine/cosine curved terrain. At the moment I am interpolating between the white "ice" and the darker "stone" texture. This is done like this:

color = mix(texture2D(ice_layer_tex, texcoord), texture2D(stone_layer_tex, texcoord), (vertex.y + amplitude) / (amplitude * 2))

结果:

It工作正常,但是如果我想添加更多纹理(例如草纹理),插值顺序是冰,石头,草,我该怎么办?我认为,没有像 mix(sampler2D [],percentages [])这样的函数?我怎么能按照这个逻辑写一个GLSL方法?

It works fine, but what could I do if I want to add more textures, for example a grass texture, so that the interpolation order is "ice, stone, grass"? I think, there isn't a function like mix(sampler2D[], percentages[])? How could I write a GLSL method following this logic?

推荐答案

mix()对于你自己可以轻松编写的东西来说,它实际上只是一个便利功能。定义是:

mix() is really just a convenience function for something you can easily write yourself. The definition is:

mix(v1, v2, a) = v1 * (1 - a) + v2 * a

或者换句话说,它计算加权平均值 v1 v2 ,两个权重 w1 w2 这是浮点值介于0.0和1.0之间,符合约束 w1 + w2 = 1.0

Or putting it differently, it calculates a weighted average of v1 and v2, with two weights w1 and w2 that are float values between 0.0 and 1.0 meeting the constraint w1 + w2 = 1.0:

v1 * w1 + v2 * w2

您可以直接概括此计算加权平均值超过2个输入。例如,对于3个输入 v1 v2 v3 ,你会使用3个权重 w1 w2 v3 满足约束 w1 + w2 + w3 = 1.0 ,并将加权平均值计算为:

You can directly generalize this to calculate a weighted average of more than 2 inputs. For example, for 3 inputs v1, v2 and v3, you would use 3 weights w1, w2 and v3 meeting the constraint w1 + w2 + w3 = 1.0, and calculate the weighted average as:

v1 * w1 + v2 * w2 + v3 * w3

对于您的示例,请确定你想要为3个纹理中的每一个使用的权重,然后使用类似的东西:

For your example, determine the weights you want to use for each of the 3 textures, and then use something like:

weightIce = ...;
weightStone = ...;
weightGrass = 1.0 - weightIce - weightStone;
color = texture2D(ice_layer_tex, texcoord) * weightIce +
        texture2D(stone_layer_tex, texcoord) * weightStone +
        texture2D(grass_layer_tex, texcoord) * weightGrass;

这篇关于GLSL着色器:在两个以上纹理之间插值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆