Bresenham 贝汉明算法

理解:给定两个点,画出两个点的连线经过的栅格。

求解思路:

1.

bresenham贝汉明算法_Bimme军的博客-CSDN博客

2.

若干计算机图形学算法实现_JulyThirteenth的博客-CSDN博客

// grid traversal
void gridTraversal(const dPoint &start, const dPoint &goal, const double resolution, std::vector &visited_grid)
`{`
    `iPoint s_grid = {static_cast(std::floor(start.x / resolution)), static_cast(std::floor(start.y / resolution))};`
    `iPoint g_grid = {static_cast(std::floor(goal.x / resolution)), static_cast(std::floor(goal.y / resolution))};`
    `dPoint vector = {goal.x - start.x, goal.y - start.y};`
    `double stepX = (vector.x > 0) ? 1 : -1;`
    `double stepY = (vector.y > 0) ? 1 : -1;`
    `double next_grid_boundary_x = (s_grid.x + stepX) * resolution;`
    `double next_grid_boundary_y = (s_grid.y + stepY) * resolution;`
    `double tMaxX = (vector.x != 0) ? (next_grid_boundary_x - start.x) / vector.x : DBL_MAX;`
    `double tMaxY = (vector.y != 0) ? (next_grid_boundary_y - start.y) / vector.y : DBL_MAX;`
    `double tDeltaX = (vector.x != 0) ? resolution / vector.x * stepX : DBL_MAX;`
    `double tDeltaY = (vector.y != 0) ? resolution / vector.y * stepY : DBL_MAX;`
    `iPoint diff = {0, 0};`
    `iPoint c_grid = {s_grid.x, s_grid.y};`
    `visited_grid.push_back(c_grid);`
    `bool negative = false;`
    `if (s_grid.x != g_grid.x && vector.x < 0)`
    `{`
        `diff.x--, negative = true;`
    `}`
    `if (s_grid.y != g_grid.y && vector.y < 0)`
    `{`
        `diff.y--, negative = true;`
    `}`
    `if (negative)`
    `{`
        `c_grid.x += diff.x;`
        `c_grid.y += diff.y;`
        `visited_grid.push_back(c_grid);`
    `}`
    `double tx = tMaxX;`
    `double ty = tMaxY;`
    `while (!(c_grid == g_grid))`
    `{`
        `if (tx < ty)`
        `{`
            `c_grid.x += stepX;`
            `tx += tDeltaX;`
        `}`
        `else`
        `{`
            `c_grid.y += stepY;`
            `ty += tDeltaY;`
        `}`
        `visited_grid.push_back(c_grid);`
    `}`
`}`

算法理解

我们首先找到当前栅格的下一个 x 和 y 方向的栅格 1 和 2 ;

计算下 1 和 2 距离开始节点的 x 向 和 y 向的距离 xd 和 yd 占起止点之间在 x y 向的距离的百分比 x% y%;

假如 x% < y% 那么下一个栅格就是 当前节点的 x 加 1 或者 -1 ;

注意更新 x% , 也就是 x% 变为了 新的当前节点到开始节点 x 向的距离占起止节点之间 x 向的距离的百分比了。

TARE 里面有类似的实现代码

你可能感兴趣的:(编程算法学习,算法)