一个非常大的数组(连续的内存块)

A very big array ( continuous chunk of memory)

我正在学习 Cocos2dx 并且正在使用平铺地图。 因此,让我们考虑以下代码:

 auto map = TMXTiledMap::create("map.tmx");
 auto layer = map->getLayer("Tile Layer 1");   
 auto gid = layer->tileGIDAt(Point(X, Y));

最后一行对我很重要。我很困惑,因为我看到了 tileGIDAt(Point):

的实现
uint32_t TMXLayer::getTileGIDAt(const Vec2& pos, TMXTileFlags* flags/* = nullptr*/)
{
    CCASSERT(pos.x < _layerSize.width && pos.y < _layerSize.height && pos.x >=0 && pos.y >=0, "TMXLayer: invalid position");
    CCASSERT(_tiles && _atlasIndexArray, "TMXLayer: the tiles map has been released");

    ssize_t idx = static_cast<int>((pos.x + pos.y * _layerSize.width));
    // Bits on the far end of the 32-bit global tile ID are used for tile flags
    uint32_t tile = _tiles[idx];

    // issue1264, flipped tiles can be changed dynamically
    if (flags) 
    {
        *flags = (TMXTileFlags)(tile & kTMXFlipedAll);
    }

    return (tile & kTMXFlippedMask);
}

所以,我很困惑,因为地图似乎在内存中表示为数组。

为什么可能?这对我很重要,因为如您所知,平铺地图可能非常大。地图的大小是什么:1000000 个图块 x 1000000 个图块。结果我们应该取一个 1000000^2 个元素的 Tile,所以我们需要一个非常长的连续内存块。但是不可能得到这么大的内存块(有可能吗?)。

请解释一下。

根据 MSDN:

The virtual address space for a process is the set of virtual memory addresses that it can use. The address space for each process is private and cannot be accessed by other processes unless it is shared. A virtual address does not represent the actual physical location of an object in memory; instead, the system maintains a page table for each process, which is an internal data structure used to translate virtual addresses into their corresponding physical addresses. Each time a thread references an address, the system translates the virtual address to a physical address.

所以大数组的分配没有问题,但还是有机会进入hip memory fragmentation

不要一次将所有地图放入内存。无论如何,玩家很难看到所有内容。取而代之的是玩家所在的方块,加上玩家周围各个方向的一定数量的方块。

然后随着玩家的移动,从磁盘上的任何地图加载新的图块信息,或者如果您执行程序图块,则生成新的图块,用您的新图块替换内存中的图块load/generate。