メインコンテンツまでスキップ

lineSDF: Linear Segment Distance Field

Point-to-Line Distance Calculation in 2D and 3D Space​

The lineSDF function family computes the shortest distance from any point to a line segment defined by two endpoints. This primitive enables line rendering, path tracing, and geometric analysis in both 2D and 3D coordinate systems.

Mathematical Foundation​

2D Line Segment Distance​

The 2D line distance uses orthogonal projection onto the line segment:

dline2D(st,a,b)=∥st−a−h⋅(b−a)∥d_{\text{line2D}}(st, a, b) = \|st - a - h \cdot (b - a)\|

where:

h=clamp((st−a)⋅(b−a)(b−a)⋅(b−a),0,1)h = \text{clamp}\left(\frac{(st - a) \cdot (b - a)}{(b - a) \cdot (b - a)}, 0, 1\right)

3D Line Distance​

The 3D version uses the cross product for perpendicular distance:

dline3D(p,a,b)=∥(p−a)×(p−b)∥∥b−a∥d_{\text{line3D}}(p, a, b) = \frac{\|(p - a) \times (p - b)\|}{\|b - a\|}

Function Signatures​

lineSDF2D (2D Line Segment)​

ParameterTypeDescription
stvec2Sample point position
avec2Line segment start point
bvec2Line segment end point

lineSDF3D (3D Line)​

ParameterTypeDescription
pvec3Sample point position
avec3Line start point
bvec3Line end point

Implementation Demonstrations​

ライブエディター

const fragment = () => {
      const a = vec2(0.2, 0.3).add(iTime.sin().mul(0.1))
      const b = vec2(0.8, 0.7).add(iTime.mul(1.3).cos().mul(0.1))
      const dist = lineSDF2D(uv, a, b)
      const line = float(0.02).smoothstep(0.005, dist)
      const endpoints = distance(uv, a).step(0.03).max(distance(uv, b).step(0.03))
      return vec4(line.mul(vec3(0.8, 0.4, 1)).add(endpoints.mul(vec3(1, 0.2, 0.3))), 1)
}
結果
Loading...