如何在仅使用顶点和索引的情况下绘制一条线?

How can I draw a line while only using vertices and indices?

我使用 wgpu 作为我项目的图形后端。

这是我当前的实现:

pub fn draw_line(
    points: Vec<[f32; 2]>,
) -> (Vec<Vertex>, Vec<u16>) {
    let mut vertices: Vec<Vertex> = Vec::new();
    let mut indices: Vec<u16> = Vec::new();

    let w = WIDTH / 2.0;

    let x1 = points[0][0];
    let x2 = points[1][0];
    let y1 = points[0][1];
    let y2 = points[1][1];

    let color: [f32; 3] = [1.0, 1.0, 1.0];

    vertices.push(Vertex { position: [x1,  y1 - w, 0.0],   color });
    vertices.push(Vertex { position: [x1,  y1 + w, 0.0],   color });
    vertices.push(Vertex { position: [x2,  y2 + w, 0.0],   color });
    vertices.push(Vertex { position: [x2,  y2 - w, 0.0],   color });

    indices.push(2);
    indices.push(1);
    indices.push(0);
    indices.push(2);
    indices.push(0);
    indices.push(3);

    return (vertices, indices);
}

但是当试图在两点之间画一条线时,线的宽度相对于这些点的高度差会扭曲。 point1 的 X 和 Y 值必须小于 point2 的 X 和 Y 值,否则它们不会显示,因为 wgpu 需要顺时针或逆时针正面

有没有比returns顶点和索引更好的函数,用于2点之间的线

未经测试但应该有效:

pub fn draw_line(
    points: Vec<[f32; 2]>,
) -> (Vec<Vertex>, Vec<u16>) {
    let mut vertices: Vec<Vertex> = Vec::new();
    let mut indices: Vec<u16> = Vec::new();

    let w = WIDTH / 2.0;

    let x1 = points[0][0];
    let x2 = points[1][0];
    let y1 = points[0][1];
    let y2 = points[1][1];

    let color: [f32; 3] = [1.0, 1.0, 1.0];

    let dx = x2 - x1;
    let dy = y2 - y1;
    let l = dx.hypot (dy);
    let u = dx * WIDTH * 0.5 / l;
    let v = dy * WIDTH * 0.5 / l;

    vertices.push(Vertex { position: [x1 + v,  y1 - u, 0.0],   color });
    vertices.push(Vertex { position: [x1 - v,  y1 + u, 0.0],   color });
    vertices.push(Vertex { position: [x2 - v,  y2 + u, 0.0],   color });
    vertices.push(Vertex { position: [x2 + v,  y2 - u, 0.0],   color });

    indices.push(2);
    indices.push(1);
    indices.push(0);
    indices.push(2);
    indices.push(0);
    indices.push(3);

    return (vertices, indices);
}