使用每个三角形/面的纯色编写 GLSL 片段着色器的方法 [英] Approach for writing a GLSL fragment shader with a solid color per triangle/face

查看:32
本文介绍了使用每个三角形/面的纯色编写 GLSL 片段着色器的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有顶点和三角形数据,其中包含每个三角形(面)的颜色,而不是每个顶点的颜色.即一个顶点被多个面共享,每个面可能有不同的颜色.

I have vertex and triangle data which contains a color for each triangle (face), not for each vertex. i.e. A single vertex is shared by multiple faces, each face potentially a different color.

我应该如何在 GLSL 中解决这个问题来为每个正在渲染的 face 分配纯色?通过平均顶点的相邻多边形的颜色来计算和分配顶点颜色"缓冲区很容易,但这当然会产生模糊的结果,其中颜色在片段着色器中被插值.

How should I approach this problem in GLSL to obtain a solid color assignment for each face being rendered? Calculating and assigning a "vertex color" buffer by averaging the colors of a vertex's neighboring polys is easy enough, but this of course produces a blurry result where the colors are interpolated in the fragment shader.

我真正需要的根本不应该是内插颜色值,一旦按预期工作,我将有大约 40k 个三角形用大约 15 种可能的纯色着色.

What I really need shouldn't be interpolated color values at all, I'll have about 40k triangles shaded with approx 15 possible solid colors once this is working as intended.

推荐答案

虽然您可能可以在高端 GLSL 中执行此操作,但进行实体着色的正确方法是为每个三角形制作独特的顶点.这是一个微不足道的循环.对于每个顶点,计算有多少三角形共享它.这就是您必须复制它的频率.确保你的循环是 O(n).然后只需将每个顶点颜色或法线设置为三角形的颜色.又是一个直线循环.不要费心去优化共享颜色,不值得.

While you maybe could do this in high end GLSL, the right way to do solid shading is to make unique vertices for every triangle. This is a trivial loop. For every vertex, count how many triangles share it. That's how often you have to replicate it. Make sure your loop to do this is O(n). Then just set each vertex color or normal to that of the triangle. Again one straight loop. Do not bother to optimize for shared colors, it is not worth it.

稍后再编辑,因为这是一个流行的答案:

Edit much later, because this is a popular answer:

要对每个面进行平面着色,您可以在世界或视图空间中插入顶点位置.然后在片段着色器中计算该变量的 ddx(dFdx) 和 ddy(dFdy).取这两个向量的叉积并将其归一化 - 您得到了平坦的法线!根本不需要网格更改或每个顶点数据.

To do flat per face shading you can interpolate the vertex position in world or view space. Then in the fragment shader compute ddx(dFdx) and ddy(dFdy) of this variable. Take the cross product of those two vectors and normalize it - you got a flat normal! No mesh changes or per vertex data needed at all.

这篇关于使用每个三角形/面的纯色编写 GLSL 片段着色器的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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