Skip to content

Commit dfeea31

Browse files
SDF polygon inside pixel shader
1 parent 23327f6 commit dfeea31

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

polygon.shader

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
Shader "Polygon"
2+
{
3+
SubShader
4+
{
5+
Pass
6+
{
7+
CGPROGRAM
8+
#pragma vertex VSMain
9+
#pragma fragment PSMain
10+
11+
static const float2 vertices[4] = {{0.2f,0.6f},{0.7f,0.2f},{0.8f,0.5f},{0.4f,0.7f}};
12+
13+
float polygon( float2 v[4], float2 p )
14+
{
15+
const int num = 4;
16+
float d = dot(p-v[0],p-v[0]);
17+
float s = 1.0;
18+
for( int i=0, j=num-1; i<num; j=i, i++ )
19+
{
20+
float2 e = v[j] - v[i];
21+
float2 w = p - v[i];
22+
float2 b = w - e*clamp( dot(w,e)/dot(e,e), 0.0, 1.0 );
23+
d = min( d, dot(b,b) );
24+
vector <bool,3> cond = { p.y>=v[i].y, p.y<v[j].y, e.x*w.y>e.y*w.x };
25+
if( all(cond) || all(!(cond)) ) s*=-1.0;
26+
}
27+
return s*sqrt(d);
28+
}
29+
30+
void VSMain (inout float4 vertex:POSITION,inout float2 uv:TEXCOORD0)
31+
{
32+
vertex = UnityObjectToClipPos(vertex);
33+
}
34+
35+
float4 PSMain (float4 vertex:POSITION,float2 uv:TEXCOORD0) : SV_TARGET
36+
{
37+
float d = polygon(vertices, uv);
38+
float3 k = step(sign(d),float3(0.0,0.0,0.0));
39+
return float4(k,1);
40+
}
41+
ENDCG
42+
}
43+
}
44+
}

0 commit comments

Comments
 (0)