opengl - GLSL片段着色器 - 绘制简单的粗曲线
问题描述
我试图在片段着色器中绘制一条非常简单的曲线,其中有一个水平部分、一个过渡部分,然后是另一个水平部分。它如下所示:
我的做法:
我没有使用贝塞尔曲线(这会使厚度变得更加复杂),而是尝试走捷径。基本上,我只使用一个平滑的步骤在水平线段之间进行过渡,从而得到一条不错的曲线。为了计算曲线的厚度,对于任何给定的片段 x,我计算 y 并最终计算我们应该在线上的位置 (x,y)。不幸的是,这不是计算到曲线的最短距离,如下所示。
下面的图表可能有助于理解我遇到问题的功能。
// Start is a 2D point where the line will start
// End is a 2d point where the line will end
// transition_x is the "x" position where we're use a smoothstep to transition between points
float CurvedLine(vec2 start, vec2 end, float transition_x) {
// Setup variables for positioning the line
float curve_width_frac = bendWidth; // How wide should we make the S bend
float thickness = abs(end.x - start.x) * curve_width_frac; // normalize
float start_blend = transition_x - thickness;
float end_blend = transition_x + thickness;
// for the current fragment, if you draw a line straight up, what's the first point it hits?
float progress_along_line = smoothstep(start_blend, end_blend, frag_coord.x);
vec2 point_on_line_from_x = vec2(frag_coord.x, mix(start.y,end.y, progress_along_line)); // given an x, this is the Y
// Convert to application specific stuff since units are a little odd
vec2 nearest_coord = point_on_line_from_x * dimensions;
vec2 rad_as_coord = rad * dimensions;
// return pseudo distance function where 1 is inside and 0 is outside
return 1.0 - smoothstep(lineWidth * dimensions.y, lineWidth * 1.2 * dimensions.y, distance(nearest_coord, rad_as_coord));
// return mix(vec4(1.0), vec4(0.0), s));
}
所以我熟悉给定一条线或线段,计算到线的最短距离,但我不太确定如何用这个曲线段处理它。任何建议将不胜感激。
解决方案
我会在 2 遍中做到这一点:
渲染细曲线
尚未使用目标颜色,而是使用 BW/灰度... 黑色背景白色线条使下一步更容易。
平滑原始图像和阈值
所以只需使用任何 FIR 平滑或高斯模糊,这将使颜色流血到厚度距离的一半。在此之后,只需将结果与背景设置阈值并重新着色为想要的颜色。平滑需要来自 #1 的渲染图像作为输入。您可以使用带有圆形掩码的简单卷积:
0 0 0 1 1 1 0 0 0 0 0 1 1 1 1 1 0 0 0 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 0 0 0 1 1 1 1 1 0 0 0 0 0 1 1 1 0 0 0
顺便提一句。像这样卷积后的颜色强度将是距中心距离的函数,因此如果需要,它可以用作纹理坐标或着色参数...
您也可以使用 2 个嵌套的 for 循环来代替卷积矩阵:
// convolution col=vec4(0.0,0.0,0.0,0.0); for (y=-r;y<=+r;y++) for (x=-r;x<=+r;x++) if ((x*x)+(y*y)<=r*r) col+=texture2D(sampler,vec2(x0+x*mx,y0+y*my)); // threshold & recolor if (col.r>threshold) col=col_curve; // assuming 1st pass has red channel used else col=col_background;
x0,y0
您在纹理中的片段位置在哪里,并且从mx,my
像素缩放到纹理坐标比例。此外,您需要处理边缘情况,x+x0
并且y+y0
可以在您的纹理之外。
当心曲线越厚,这将变得越慢......对于更高的厚度来说,应用更小的半径平滑几次(更多的通行证)更快
这里有一些相关的QA可以涵盖一些步骤:
- OpenGL Scale Single Pixel Line for multi pass (old api)
- 如何在 GLSL扫描输入纹理中实现 2D 光线投射光效
推荐阅读
- java - 在 java 中使用 GZIPOutputStream 或 ZIPOutputStream 时是否可以排除文件和/或目录?
- ios - 内容左对齐 - SwiftUI iOS 14 Widget
- java - 文件中的数字
- parallel-processing - 在 2020 年,在一台计算机上的多个 GPU 上使用 Pytorch 训练模型的最佳方式是什么?
- python - 为什么要创建一个二进制列来指示具有缺失值的记录
- python - 在 python 中打印列表有不同的方法吗?
- neo4j - 计算最短路径neo4j后的节点数
- node.js - 有没有办法查看有多少用户加入了我的不和谐机器人游戏?
- pandas - xarray,用多维坐标索引
- typescript - 我收到了 CannotDetermineGraphQLTypeError 并且无法修复它