【问题标题】:In a hexagon graph, how do I store 3D coordinates as an index for a 1D container / retrieve an element from a 1D container using 3D coordinates?在六边形图中,如何将 3D 坐标存储为 1D 容器的索引/使用 3D 坐标从 1D 容器中检索元素?
【发布时间】:2020-02-16 11:09:38
【问题描述】:

我正在尝试使用立方坐标存储六边形图,详见https://www.redblobgames.com/grids/hexagons/#coordinates

我想使用向量或一些易于迭代的容器来存储 Hex 对象,基本上是 3D 整数坐标的集合加上包含相邻 Hex 索引的向量。

我的问题是我无法想出将立方 X/Y/Z 坐标(允许负整数值)转换为相应的 1D 容器索引的函数。给定任何有效的坐标集,我希望能够获得十六进制的特定索引号。

我知道有一个类似的功能

1D_index = f(x,y,z) = x + (max_width)*y + (max_width)(max_height)*z,

对于笛卡尔网格,但我无法在六边形空间中生成类似的函数:

我的 Hex 类和容器是这样的:

class Hex
{
private:
    int xCell, yCell, zCell;
    std::vector<int>neighbours;

public:
    Hex();
    Hex(int x, int y, int z) : _x(x), _y(y), _z(z);
    ~Hex();
};


std::vector<Hex*>hexGraph;

为了用未连接的节点填充图形,我只列出了所有可能存在的坐标,给定图形的正负 x/y/z 维度:


for(int x = effectiveWorldNegX; x < effectiveWorldPosX; x++)
        for(int y = effectiveWorldPosY; y > effectiveWorldNegY; y--)
            hexGraph.push_back(new Hex(x,y,(x*-1)-y)); // x+y+z=0, so z=(-x-y)

现在我被难住了。我想使用这样的循环连接节点:

for(std::vector<Hex*>iterator it = hexGraph.begin(); it != hexGraph.end(); ++it)
{
(*it)->neighbours.push_back( /* Index of upper left hex node */ )
(*it)->neighbours.push_back( /* Index of upper center hex node */ )
(*it)->neighbours.push_back( /* Index of upper right hex node */ )
...

}

等等,但为了做到这一点,我需要一种方法来找到任何单元格 +1x、-1y、+0z 的索引。

从上面的循环中,我确定的是 1) 给定循环的开始/结束,将 Hex 推回 hexGraph 向量的确切顺序

2) 我可能需要也可能不需要将所有坐标值偏移 X/Y/Z 与 0 的负距离以去除负值

但是我可以从这里去哪里?

非常感谢您的帮助。

【问题讨论】:

    标签: c++ containers coordinates


    【解决方案1】:

    解决此问题的一种方法是为图形的每个顶点提供id,然后通过 id 引用相邻顶点。

    例子

    using VertexId = size_t;
    
    class Hex {
        std::vector<VertexId>neighbours;
      public:
        Hex(int x, int y, int z);
    };
    
    class VertexStorage {    
        std::unordered_map<VertexId, Hex> _id_to_hex;
        std::unordered_map<Hex, VertexId> _hex_to_id;
      public:
        // check if hex is in storage, return id
        // if not, assign new id an push tostorage
        // id could be increasing counter
        VertexId getId(const Hex &hex);
        Hex getHex(VertexId id);
    };
    

    【讨论】:

      猜你喜欢
      • 2012-07-27
      • 1970-01-01
      • 2021-04-16
      • 2022-11-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-14
      • 1970-01-01
      相关资源
      最近更新 更多