我需要一个可以引用7000万+ texture2d / vector2对象集的容器

时间:2011-06-08 13:32:10

标签: c# .net collections xna

我正在尝试找到一种存储大约7000万个texture2d / vector2集的引用的方法。为了澄清一点,我需要能够使用100左右的texture2d然后为它们分配一个vector2 XY值,用于具有大约7000万个tile的tile map。我只需要参考哪个texture2d与哪个vector2一起使用。我将动态/程序性地生成tile /坐标集我只需要一种存储所有这些的方法,现在不会炸毁我的ram。我试图使用一个字典,其中vector2作为键,而texture2d作为值,但是使用OutOfMemoryException杀死了我。然后我尝试了Wintellect Power Collections并使用了他们的MultiDictionary。但是,即使我将texture2d指定为唯一的键并使用vector2作为该键的7000万个值,它仍然会使用相同的异常终止。

所以我现在不知道该怎么办。我只需要存储引用以供以后访问。我不是想把它们画到屏幕上或类似的东西所以我无法弄清楚为什么只需要字典就需要700mb的ram。后来我才意识到我一直在让这些词典自己调整大小。这可能是问题吗?

我希望这已经足够具体我已经整晚都在忙,所以我现在不打算清理和发布任何代码。如果您认为我的代码是罪魁祸首而不是我的方法,请告诉我,我会为您发布。期待您的回答。

编辑:好的,这是我正在使用的代码。我清理了一下,但我知道它不是最好看的代码。如果您发现任何明显的问题或甚至效率低下,我会很高兴听到他们的消息。只是不要狠狠地打击我,因为这是我第一次使用c#:)

当WorldWidth& amp; WorldHeight分别为8400。

class MapMaker
{
    SpriteSheet spriteSheetMap;
    SpriteSheet spriteSheet1;
    SpriteSheet spriteSheet2;
    SpriteSheet spriteSheet3;
    SpriteSheet spriteSheet4;
    SpriteSheet spriteSheet5;
    SpriteSheet spriteSheet6;
    SpriteSheet spriteSheet7;
    SpriteSheet spriteSheet8;
    SpriteSheet spriteSheet9;
    SpriteSheet spriteSheet10;
    SpriteSheet spriteSheet11;
    SpriteSheet spriteSheet12;
    SpriteSheet spriteSheet13;
    SpriteSheet spriteSheet14;
    SpriteSheet spriteSheet15;
    SpriteSheet spriteSheet16;
    SpriteSheet spriteSheet17;
    SpriteSheet spriteSheet18;
    SpriteSheet spriteSheet19;
    SpriteSheet spriteSheet20;
    SpriteSheet spriteSheet21;
    SpriteSheet spriteSheet22;
    SpriteSheet spriteSheet23;

    Random rnd = new Random();

    int WorldWidth = 250;
    int WorldHeight = 250;
    List<int> sprites = new List<int>();
    int[][] TheGrid = new int[10][];
    int posX = 0, posY = 0, gridX = 0, gridY = 0;
    Dictionary<int, Texture2D> TileStorage = new Dictionary<int, Texture2D>();
    Dictionary<Vector2, Texture2D> SineSaver = new Dictionary<Vector2, Texture2D>();
    public void loadTiles(ContentManager Content)
    {
        spriteSheetMap = new SpriteSheet();

        spriteSheet1 = new SpriteSheet();
        spriteSheet2 = new SpriteSheet();
        spriteSheet3 = new SpriteSheet();
        spriteSheet4 = new SpriteSheet();
        spriteSheet5 = new SpriteSheet();
        spriteSheet6 = new SpriteSheet();
        spriteSheet7 = new SpriteSheet();
        spriteSheet8 = new SpriteSheet();
        spriteSheet9 = new SpriteSheet();
        spriteSheet10 = new SpriteSheet();
        spriteSheet11 = new SpriteSheet();
        spriteSheet12 = new SpriteSheet();
        spriteSheet13 = new SpriteSheet();
        spriteSheet14 = new SpriteSheet();
        spriteSheet15 = new SpriteSheet();
        spriteSheet16 = new SpriteSheet();
        spriteSheet17 = new SpriteSheet();
        spriteSheet18 = new SpriteSheet();
        spriteSheet19 = new SpriteSheet();
        spriteSheet20 = new SpriteSheet();
        spriteSheet21 = new SpriteSheet();
        spriteSheet22 = new SpriteSheet();
        spriteSheet23 = new SpriteSheet();

        spriteSheetMap.Map = Content.Load<Dictionary<string, Rectangle>>("Tiles/Map");
        TileStorage.Add(0, spriteSheet1.Sheet = Content.Load<Texture2D>("test2"));
        TileStorage.Add(1, spriteSheet1.Sheet = Content.Load<Texture2D>("Tiles/Amethyst"));
        TileStorage.Add(2, spriteSheet2.Sheet = Content.Load<Texture2D>("Tiles/Amethyst_N"));
        TileStorage.Add(3, spriteSheet3.Sheet = Content.Load<Texture2D>("Tiles/Aquamarine"));
        TileStorage.Add(4, spriteSheet4.Sheet = Content.Load<Texture2D>("Tiles/Aquamarine_N"));
        TileStorage.Add(5, spriteSheet5.Sheet = Content.Load<Texture2D>("Tiles/Citrine"));
        TileStorage.Add(6, spriteSheet6.Sheet = Content.Load<Texture2D>("Tiles/Citrine_N"));
        TileStorage.Add(7, spriteSheet7.Sheet = Content.Load<Texture2D>("Tiles/Diamond"));
        TileStorage.Add(8, spriteSheet8.Sheet = Content.Load<Texture2D>("Tiles/Diamond_N"));
        TileStorage.Add(9, spriteSheet9.Sheet = Content.Load<Texture2D>("Tiles/Dirt1"));
        TileStorage.Add(10, spriteSheet10.Sheet = Content.Load<Texture2D>("Tiles/Dirt2"));
        TileStorage.Add(11, spriteSheet11.Sheet = Content.Load<Texture2D>("Tiles/Emerald"));
        TileStorage.Add(12, spriteSheet12.Sheet = Content.Load<Texture2D>("Tiles/Emerald_N"));
        TileStorage.Add(13, spriteSheet13.Sheet = Content.Load<Texture2D>("Tiles/Peridot"));
        TileStorage.Add(14, spriteSheet14.Sheet = Content.Load<Texture2D>("Tiles/Peridot_N"));
        TileStorage.Add(15, spriteSheet15.Sheet = Content.Load<Texture2D>("Tiles/Ruby"));
        TileStorage.Add(16, spriteSheet16.Sheet = Content.Load<Texture2D>("Tiles/Ruby_N"));
        TileStorage.Add(17, spriteSheet17.Sheet = Content.Load<Texture2D>("Tiles/Sand"));
        TileStorage.Add(18, spriteSheet18.Sheet = Content.Load<Texture2D>("Tiles/Sapphire"));
        TileStorage.Add(19, spriteSheet19.Sheet = Content.Load<Texture2D>("Tiles/Stone1"));
        TileStorage.Add(20, spriteSheet20.Sheet = Content.Load<Texture2D>("Tiles/Stone2"));
        TileStorage.Add(21, spriteSheet21.Sheet = Content.Load<Texture2D>("Tiles/Stone3"));
        TileStorage.Add(22, spriteSheet22.Sheet = Content.Load<Texture2D>("Tiles/Topaz"));
        TileStorage.Add(23, spriteSheet23.Sheet = Content.Load<Texture2D>("Tiles/Topaz_N"));

        CreateMapKey();
    }

    private void CreateMapKey()
    {
        TheGrid[0] = new int[] { 0, 3, 14, 25, 36, 47, 58, 69, 80, 91 };
        TheGrid[1] = new int[] { 12, 4, 15, 26, 37, 48, 59, 70, 81, 92 };
        TheGrid[2] = new int[] { 23, 5, 16, 27, 38, 49, 60, 71, 82, 93 };
        TheGrid[3] = new int[] { 34, 6, 17, 28, 39, 50, 61, 72, 83, 94 };
        TheGrid[4] = new int[] { 45, 7, 18, 29, 40, 51, 62, 73, 84, 95 };
        TheGrid[5] = new int[] { 56, 8, 19, 30, 41, 52, 63, 74, 85, 96 };
        TheGrid[6] = new int[] { 67, 9, 20, 31, 42, 53, 64, 75, 86, 97 };
        TheGrid[7] = new int[] { 78, 10, 21, 32, 43, 54, 65, 76, 87, 98 };
        TheGrid[8] = new int[] { 89, 11, 22, 33, 44, 55, 66, 77, 88, 99 };
        TheGrid[9] = new int[] { 1, 13, 24, 35, 46, 57, 68, 79, 90, 2 };

        BaseTileset();
    }

    private void BaseTileset()
    {
        int hillLocation = 300, hillWidth = 120, hillHeight = 10;
        for (int i = 0; i < WorldHeight * WorldWidth; i++)
        {
            if (i % WorldHeight * 5 == 0)
            {
                hillLocation += rnd.Next(-40, 40);
                hillWidth += rnd.Next(-10, 10);
                if (hillWidth == 0) { hillWidth = 1; }
                hillHeight += rnd.Next(-5, 5);
            }
            Vector2 position = new Vector2(posX, posY);
            Texture2D tile = TileStorage[9];
            double sine = hillLocation + Math.Sin(posX / hillWidth) * hillHeight;
            double cosine = hillLocation + Math.Cos(posX / hillWidth) * hillHeight / 2;
            if (posY <= sine || posY < cosine)
            {
                tile = null;
            }
            if (tile != null)
            {
                SineSaver.Add(position, tile);
                sprites.Add(TheGrid[gridY][gridX]);

            }

            posY += 20;
            if (posY > (WorldHeight - 1) * 20) { posY = 0; posX += 20; }
            gridX = posX / 20 % 10;
            gridY = posY / 20 % 10;
        }

    }

    public void DrawLevel(SpriteBatch spriteBatch, GraphicsDeviceManager graphics)
    {
        spriteBatch.Begin();
        int i = 0;
        foreach (KeyValuePair<Vector2, Texture2D> entry in SineSaver)
        {
            spriteBatch.Draw(entry.Value, entry.Key, spriteSheetMap[sprites[i]], Color.White);
            i++;
        }
        spriteBatch.End();
    }
}

4 个答案:

答案 0 :(得分:7)

我建议调查flyweight模式(http://en.wikipedia.org/wiki/Flyweight_pattern

如果您知道每个图块的宽度和高度,则可以计算每个图块的Vector2位置 - 它是基于索引的确定性的,因此不需要存储。每个磁贴所需的唯一数据是索引的一个int,以及一个可以小到单个字节的“类型”标识符。

7000万*(4 + 1)字节= 333.786011兆字节

编辑1:略微阐述..

假设我们有一个3x3的瓷砖网格 - 我们知道总共有9个瓷砖,所以我们为每个瓷砖分配0-8的索引。

Tile[] tiles = new Tile[9]

for (int i = 0; i < 9; i++)
    tiles[i].Index = i;

知道每个网格行是3个图块,并且每个图块3向下拼贴,我们可以使用模数和除法运算符来获得行和&amp;任何瓷砖索引的列......

Tile tile = getSomeTile();

int column = tile.Index % 3; // = column 1
int row = tile.Index \ 3; // = row 1 - tile 4 is in the middle :)

知道每个瓷砖的宽度和高度(比如说10个像素)我们现在可以计算出瓷砖4的确切位置:

Vector2 position = new Vector2
{
    X = 10f * column,
    Y = 10f * row
};

编辑2:回复评论......

你的Tile对象需要包含一个类型标识符,如下所示:

struct Tile
{
    int Index; // The tiles index in the map [0 - 70 million].
    byte TileTypeId; // An identifier for a tile type.
}

class TileType // This is the flyweight object..
{
    Texture2D Texture; // Gets the texture reference for the tile type...

    // any other information about the tile ie. is it collidable? is it water? etc..
}

然后谈到绘制瓷砖......

Tile tile = tiles[someIndex];

TileType type = tileTypes[tile.TileTypeId];  // tileTypes could be a dictionary...

Vector2 position = this.CalculateTilePosition(tile.Index); // Calculate the position as above...

spriteBatch.Draw(type.Texture, position);

编辑3:响应序列化评论...

序列化tile网格应该非常简单,它只是一个looong字节序列。假设瓷砖按顺序存储,我们已经知道瓷砖索引号,因此不需要存储在文件中。

返回3x3网格示例:

Example binary data file:
0xF4 0x15 0x5A 0xB5 0x00 0x61 0xEE 0xA3 0x39

BinaryReader reader = OpenSomeBinaryFile();

for (int i = 0; i < (3 * 3); i++)
    tiles[i] = new Tile { Index = i, TileTypeId= reader.ReadByte() };

// easy to optimize by reading bigger binary chunks (say an Int64) and bit shifting to get the individual bytes...

// If you happen to have reasonbly large series of tiles with the same type id (byte), the file will be quite well suited to compression on disk, which is a bonus :)

答案 1 :(得分:1)

为了避免极端的内存问题(即使每个磁贴1个字节有7000万个磁贴是70Mb),您可能需要考虑某种流式实现。 最基本的东西,比如包含NxN图块的WorldChunk,以及指向另一个WorldChunk的链接(直接链接,或只是ID或字符串来标识它)。这些块中的每一个都可以具有OnEnterFrame和OnExitFrame方法。

在OnEnterFrame方法中,您可以在所有链接的块上调用文件加载,这些文件将使用游戏文件中的数据填充它们,而OnExit则会销毁它们。在这种情况下,你只会保留一小部分块,这是8400x8400世界的一部分。 3x3或5x5是不错的选择。理想情况下,这些块会填满屏幕或略高于屏幕。

伪代码概念如下:

class WorldChunk
{
    String MyName;
    String[8] LinkedWorldChunkFileNames; 
    Tile[32,32] Tiles;
    void OnEnterFrame()
    {
        LoadWorldChunkFromName(MyName);
        foreach(name in LinkedWorldChunkFileNames)
        {
            LoadWorldChunkFromName(name);
        }
    }

    void LoadWorldChunkFromName(string name)
    {
        string fileData = LoadFromFile(name); //this should probably be done earlier, 
                                              //when a neighbor loads it should load
                                              // offscreen nieghbors
                                              //files then parse them on its own enter                                        
                                              //frame
        Tiles = ParseToTiles(fileData); //your own file parsing here
    }

    void OnExitFrame()
    {
        Tiles.Clear();
    }
}

我还没有实现这样的东西,但是我也开始考虑这个问题,因为我需要在3d中做一些非常相似的事情。

答案 2 :(得分:0)

为什么不直接创建一个扩展Vector2的类,而是在构造函数中使用一个额外的变量来说明哪个Texture2D属于它?这样一切都将存储在对象本身中,这非常有效。所以你可能不需要任何其他数据结构!

编辑或者甚至只创建一个包含所有可能纹理的数组,然后只为自定义对象提供一个索引。这样您就不必每次都复制整个Texture2D对象了!

编辑2:因为(我应该知道并且已经向我指出)你不能扩展到Vector2,我会做这样的事情:

 public class TextureVector2D
 {
     public Vector2D vector;
     public int textureIndex;

     public TextureVector2D( Vector2D v, int tI )
     {
          vector = v;
          textureIndex = tI;
      }
 }

答案 3 :(得分:0)

所以我不知道如果你的spritesheets里面有多个瓷砖或者诸如此类的......但是你可以这样做:

class GameTile 
{
    private Vector2D _vec;
    //These integers should be sized to fit your needs
    //int8 = up to 256 tilesets
    //int16 = up to 65536 tiles in a set
    private int8 _tileSet;
    private int16 _tileIndex;

    //This is the tiles position in the world
    public Vector2D Position { get { return _vec; } }
    //This is the index of the tileset in the array of all tilesets
    public int8 CurrentTileset { get { return _tileSet; } }
    //This is the flattened index (row * width + column) 
    //of the tile in the tileset
    public int16 CurrentTile { get { return _tileIndex; } }        
}