用于存储基于2D单元格的GameObjects地图的数据结构是什么?

时间:2017-03-22 10:55:01

标签: c++ arrays c++11 dictionary stl

我知道你可能正在考虑2D数组或2D矢量,但是请听我说。

我实际上已经在使用二维数组来制作瓷砖地图,效果很好。但是,我正在尝试开发一种数据结构,可以将游戏对象存储在位于此类tilemap的顶部上。

我的要求如下:

  • 对象图必须允许许多对象位于同一个单元格

  • 对象图必须可以按行和列进行迭代,这样我就可以将迭代空间剔除到某些坐标(这样我只能渲染实际在屏幕上的对象,等等) / p>

  • 优选地,对象图还应提供快速查找以确定 1:给定单元格中的对象, 2:当前是否存在给定对象在某个对象地图上 3:对象地图上给定对象的位置

我已经起草了一个使用两个STL容器的基本数据结构:

  • 3D std::map<int, std::map<int, std::vector<Object*>>>用于提供可迭代的,容易被淘汰的容器。使用std :: vector,以便可以在同一个单元格中包含许多对象。也可以通过_map [x] [y]访问单元格。

  • 此外,我使用的是1D std::map<Object*, Vec2<int>*>,它包含与3D std :: map完全相同的对象,但我认为它会允许更快的搜索,因为它是1D。 Vec2<int>*是指针的原因是GameObject可以向ObjectMap询问它在地图上的位置,可能保存它,然后在不需要搜索的情况下立即访问它。

根据我的要求,是否有比我使用过的容器更合适的容器?

如果有帮助,我已经为下面的ObjectMap粘贴了我的代码:

#pragma once
#include <vector>
#include <map>

template<typename T>
struct Vec2 {
    Vec2() { x = 0; y = 0; }
    Vec2(T xVal, T yVal) : x(xVal), y(yVal) {}
    void Set(T xVal, T yVal) { x = xVal; y = yVal; }
    T x, y;
    Vec2& operator+=(const Vec2& rhs) { x += rhs.x; y += rhs.y; return *this; }
    Vec2 operator+(const Vec2& rhs) { return Vec2<T>(x + rhs.x, y + rhs.y); }
};

/// <summary>
/// Represents a map of objects that can be layered on top of a cell-based map
/// Allows for multiple objects per map cell
/// </summary>
template <typename Object>
class ObjectMap {
public:
    /// <summary>
    /// Gets the objects located at the given map cell
    /// </summary>
    /// <param name="row">The row of the cell to inspect</param>
    /// <param name="column">The column of the cell to inspect</param>
    /// <returns>
    /// A pointer to a vector of objects residing at the given cell.
    /// Returns a nullptr if there are no objects at the cell.
    /// </returns>
    std::vector<Object*>* At(int row, int column);

    /// <summary>
    /// Checks whether the ObjectMap contains the given object
    /// </summary>
    /// <param name="object">A pointer to the object to check for</param>
    /// <returns>True if the ObjectMap contains the object</returns>
    bool Contains(Object* object);

    /// <summary>
    /// Adds the given object to the ObjectMap at the given cell
    /// </summary>
    /// <param name="object">The object to add to the map</param>
    /// <param name="row">The row of the cell to add the object to</param>
    /// <param name="column">The column of the cell to add the object to</param>
    /// <returns>True if successful, false if the object is already in the ObjectMap</returns>
    bool Add(Object* object, int row, int column);

    /// <summary>
    /// Moves the given object by some number of rows and columns
    /// </summary>
    /// <param name="object">The object to move</param>
    /// <param name="rows">The number of rows to move the object by</param>
    /// <param name="columns">The number of columns to move the object by</param>
    /// <returns>True if successful, false if the object does not exist in the ObjectMap</returns>
    bool MoveBy(Object* object, int rows, int columns);

    /// <summary>
    /// Moves the given object to the given cell
    /// </summary>
    /// <param name="object">The object to move</param>
    /// <param name="row">The row of the cell to move the object to</param>
    /// <param name="column">The column of the cell to move the object to</param>
    /// <returns>True if successful, false if the object does not exist in the ObjectMap</returns>
    bool MoveTo(Object* object, int row, int column);

    /// <summary>
    /// Gets the position of the given object
    /// </summary>
    /// <param name="object">A pointer to the object to check the position of</param>
    /// <returns>
    /// A pointer to the position of the object.
    /// Returns a nullptr if the object does not exist in the ObjectMap.
    /// </returns>
    Vec2<int>* GetPosition(Object* object);
private:
    /// <summary>
    /// A 3D container allowing object access via cell positions
    /// Provides the ability to iterate across sections of the map
    /// Useful for object culling and rendering
    /// Useful for object lookup when the position is known
    /// Example: _map[a][b] is a vector objects positioned at the map cell (x=a,y=b)
    /// </summary>
    std::map<int, std::map<int, std::vector<Object*>>> _map;

    /// <summary>
    /// A 1D container of all objects and pointers to their positions
    /// Useful for quickly checking whether an object exists
    /// Useful for quickly getting the location of an object
    /// </summary>
    std::map<Object*, Vec2<int>*> _objects;
};

/// 
/// ObjectMap.tpp
/// The implementation has not been separated into a .cpp file because templated 
/// functions must be implemented in header files.
/// 
/// See http://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file
/// 
#include <algorithm>

template <typename Object>
std::vector<Object*>* ObjectMap<Object>::At(int column, int row) {
    // Checks whether a key exists for the given column
    if (_map.find(column) != _map.end()) {
        // Checks whether a key exists for the given row
        if (_map.at(column).find(row) != _map.at(column).end()) {
            // Return the objects residing in the cell
            return &_map.at(column).at(row);
        }
    }
    return nullptr;
}

template <typename Object>
bool ObjectMap<Object>::Contains(Object* object) {
    return _objects.find(object) != _objects.end();
}

template <typename Object>
bool ObjectMap<Object>::Add(Object* object, int column, int row) {
    if (!Contains(object)) {
        _objects[object] = new Vec2<int>(column, row);
        _map[column][row].push_back(object);
        return true;
    }
    return false;
}

template <typename Object>
bool ObjectMap<Object>::MoveBy(Object* object, int columns, int rows) {
    Vec2<int> newPosition = *_objects[object] + Vec2<int>(columns, rows);
    return MoveTo(object, newPosition.x, newPosition.y);
}

template <typename Object>
bool ObjectMap<Object>::MoveTo(Object* object, int column, int row) {
    if (Contains(object)) {
        // Get the position reference of the object
        Vec2<int>* position = _objects[object];

        // Erase the object from its current position in the map
        auto *oldTile = &_map[position->x][position->y];
        oldTile->erase(std::remove(oldTile->begin(), oldTile->end(), object), oldTile->end());

        // Erase any newly-empty keys from the map
        if (oldTile->size() == 0) {
            _map[position->x].erase(_map[position->x].find(position->y));
            if (_map[position->x].size() == 0) {
                _map.erase(_map.find(position->x));
            }
        }

        // Add the object to its new position on the map
        _map[column][row].push_back(object);

        // Set the position of the object
        position->Set(column, row);

        return true;
    }

    return false;
}

template <typename Object>
Vec2<int>* ObjectMap<Object>::GetPosition(Object * object) {
    if (Contains(object)) {
        return _objects[object];
    }
    return nullptr;
}

2 个答案:

答案 0 :(得分:3)

您可能希望查看二进制空间分区,它可以提供非常快的查找时间,例如屏幕上的对象。

对于网格,一个良好的空间结构是QuadTrees。

答案 1 :(得分:1)

你留下了一个未指明问题的重要部分:你的地图单元中有多少比例没有获得持有物体?

  • 如果该百分比非常高(至少95%),您的map<int, map<int, vector<>>>方法看起来不错。

  • 如果该百分比很高,vector<map<int, vector<>>>会更好。

  • 如果该百分比适中(在接近50%或更低的任何地方),您应该选择vector<vector<vector<>>>

这背后的原因是,std::vector<>在实际使用大多数元素的情况下比std::map<int, >更有效。索引到std::vector<>意味着只需要一点指针算术和单个内存访问,而索引到std::map<>意味着O(log(n))内存访问。对于128个条目,这已经是7的因素。 std::map<>仅具有在未使用的索引存在的情况下减少内存消耗的优势,这可能会使稀疏使用的std::vector<>膨胀。

现在,如果你的未使用单元的数量不是很高,你必须期望你的2D数组的每一行都充满了某些东西。因此,保持线条的容器应为vector<>。如果您希望条目密度合适,那么对于行本身使用vector<>也是如此。

如果您的对象在任何给定时间内只能位于地图中的单个位置,您可能还会考虑将它们链接到侵入式链接列表中。在这种情况下,您可以将地图容器从3D放到2D,然后迭代恰好位于同一个bin中的对象的链接列表。

当然,只要预期对象的链接列表非常小,这只是一个有效的选项。