首页 > 解决方案 > 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));
}

所以我熟悉给定一条线或线段,计算到线的最短距离,但我不太确定如何用这个曲线段处理它。任何建议将不胜感激。

标签: openglglslfragment-shader

解决方案


我会在 2 遍中做到这一点:

  1. 渲染细曲线

    尚未使用目标颜色,而是使用 BW/灰度... 黑色背景白色线条使下一步更容易。

  2. 平滑原始图像和阈值

    所以只需使用任何 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可以涵盖一些步骤:


推荐阅读