Skip to content

Commit 149fd66

Browse files
committed
Font alignment
1 parent 592ad45 commit 149fd66

2 files changed

Lines changed: 12 additions & 3 deletions

File tree

webgpu/shaders/font.wgsl

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ struct FontUniforms {
1212
fn fontGetTexCoord(char: u32, vertexId: u32) -> vec2<f32> {
1313
return vec2<f32>(
1414
f32((char - 32) * u_font.width),
15-
f32(u_font.height)
15+
f32(u_font.height-1)
1616
);
1717
}
1818

@@ -25,7 +25,7 @@ struct FontFragmentInput {
2525
fn fragmentFont(@location(0) tex_coord: vec2<f32>) -> @location(0) vec4<f32> {
2626
let alpha: f32 = textureLoad(
2727
u_font_texture,
28-
vec2i(floor(tex_coord)),
28+
vec2i(tex_coord+0.5),
2929
0
3030
).x;
3131

@@ -47,7 +47,7 @@ fn fontCalc(char: u32, position: vec4<f32>, vertexId: u32) -> FontFragmentInput
4747

4848
if vertexId == 1 || vertexId == 2 || vertexId == 4 {
4949
p.x += u_font.width_normalized * p.w;
50-
tex_coord.x += f32(u_font.width);
50+
tex_coord.x += f32(u_font.width-1);
5151
}
5252
return FontFragmentInput(p, tex_coord);
5353
}

webgpu/shaders/text.wgsl

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,5 +56,14 @@ fn vertexText(@builtin(vertex_index) vertexId: u32, @builtin(instance_index) cha
5656
position.x += w * shift.x * f32(text.length);
5757
position.y += h * shift.y;
5858

59+
// snap position to pixel grid
60+
let resolution = vec2f(f32(u_font.width), f32(u_font.height)) / vec2f(u_font.width_normalized, u_font.height_normalized);
61+
let ndc = position.xy / position.w;
62+
let screen = (ndc * 0.5 + vec2f(0.5)) * resolution;
63+
let snapped_screen = floor(screen) + 0.5;
64+
let snapped_ndc = (snapped_screen / resolution - vec2f(0.5)) * 2.0;
65+
position.x = snapped_ndc.x * position.w;
66+
position.y = snapped_ndc.y * position.w;
67+
5968
return fontCalc(text.char, position, vertexId);
6069
}

0 commit comments

Comments
 (0)