@@ -57,22 +57,13 @@ fn vs_main(vertex: Vertex, quad: QuadInstance) -> VertexOutput {
5757 return out ;
5858}
5959
60- // SFD code is licenced under: MIT by Héctor Ramón & Iced contributors
61- fn distance_alg (
62- frag_coord : vec2 <f32 >,
63- position : vec2 <f32 >,
64- size : vec2 <f32 >,
65- radius : f32
66- ) -> f32 {
67- var inner_half_size : vec2 <f32 > = (size - vec2 <f32 >(radius , radius ) * 2 .0 ) / 2 .0 ;
68- var top_left : vec2 <f32 > = position + vec2 <f32 >(radius , radius );
69- return rounded_box_sdf (frag_coord - top_left - inner_half_size , inner_half_size , 0 .0 );
70- }
71-
72- // Given a vector from a point to the center of a rounded rectangle of the given `size` and
73- // border `radius`, determines the point's distance from the nearest edge of the rounded rectangle
60+ // Point's distance from the nearest edge of the rounded rectangle
61+ //
62+ // https://www.shadertoy.com/view/Nlc3zf
7463fn rounded_box_sdf (to_center : vec2 <f32 >, size : vec2 <f32 >, radius : f32 ) -> f32 {
75- return length (max (abs (to_center ) - size + vec2 <f32 >(radius , radius ), vec2 <f32 >(0 .0 , 0 .0 ))) - radius ;
64+ let half_size = size * 0 .5 ;
65+ let q = abs (to_center ) - half_size + vec2 (radius , radius );
66+ return length (max (q , vec2 (0 .0 ))) + min (max (q . x , q . y ), 0 .0 ) - radius ;
7667}
7768
7869// Based on the fragment position and the center of the quad, select one of the 4 radii.
@@ -89,24 +80,17 @@ fn select_border_radius(radii: vec4<f32>, position: vec2<f32>, center: vec2<f32>
8980
9081@fragment
9182fn fs_main (in : VertexOutput ) -> @location (0 ) vec4 <f32 > {
92- var border_radius = select_border_radius (
83+ let center = in . quad_position + in . quad_size * 0 .5 ;
84+
85+ let border_radius = select_border_radius (
9386 in . quad_border_radius ,
9487 in . position . xy ,
95- ( in . quad_position + ( in . quad_size * 0 .5 )) . xy
88+ center
9689 );
9790
98- var dist : f32 = distance_alg (
99- vec2 <f32 >(in . position . x , in . position . y ),
100- in . quad_position ,
101- in . quad_size ,
102- border_radius
103- );
104-
105- var alpha : f32 = 1 .0 - smoothstep (
106- max (border_radius - 0 .5 , 0 .0 ),
107- border_radius + 0 .5 ,
108- dist
109- );
91+ let local_center = in . position . xy - center ;
92+ let dist = rounded_box_sdf (local_center , in . quad_size , border_radius );
93+ let alpha = 1 .0 - smoothstep (- 0 .5 , 0 .5 , dist );
11094
11195 return vec4 (in . quad_color . xyz , in . quad_color . w * alpha );
11296}
0 commit comments