tilematrix_type.hpp
Go to the documentation of this file.00001
00002
00003
00004
00005
00006
00007
00008
00009
00012 #ifndef TILEMATRIX_TYPE_HPP
00013 #define TILEMATRIX_TYPE_HPP
00014
00015 #include "core/mem_func.hpp"
00016 #include "tilearea_type.h"
00017
00028 template <typename T, uint N>
00029 class TileMatrix {
00030 TileArea area;
00031
00032 T *data;
00033
00034 void AllocateStorage(TileIndex tile)
00035 {
00036 uint old_left = TileX(this->area.tile) / N;
00037 uint old_top = TileY(this->area.tile) / N;
00038 uint old_w = this->area.w / N;
00039 uint old_h = this->area.h / N;
00040
00041
00042
00043 uint grid_x = (TileX(tile) / N) * N;
00044 uint grid_y = (TileY(tile) / N) * N;
00045 this->area.Add(TileXY(grid_x, grid_y));
00046 this->area.Add(TileXY(grid_x + N - 1, grid_y + N - 1));
00047
00048
00049 T *new_data = CallocT<T>(this->area.w / N * this->area.h / N);
00050
00051 if (old_w > 0) {
00052
00053 uint offs_x = old_left - TileX(this->area.tile) / N;
00054 uint offs_y = old_top - TileY(this->area.tile) / N;
00055
00056 for (uint row = 0; row < old_h; row++) {
00057 MemCpyT(&new_data[(row + offs_y) * this->area.w / N + offs_x], &this->data[row * old_w], old_w);
00058 }
00059 }
00060
00061 free(this->data);
00062 this->data = new_data;
00063 }
00064
00065
00066 friend const struct SaveLoad *GetTileMatrixDesc();
00067 friend void RealSave_TOWN(struct Town *t);
00068 friend void Load_TOWN();
00069
00070 public:
00071 static const uint GRID = N;
00072
00073 TileMatrix() : area(INVALID_TILE, 0, 0), data(NULL) {}
00074
00075 ~TileMatrix()
00076 {
00077 free(this->data);
00078 }
00079
00084 const TileArea& GetArea() const
00085 {
00086 return this->area;
00087 }
00088
00095 static TileArea GetAreaForTile(TileIndex tile, uint extend = 0)
00096 {
00097 uint tile_x = (TileX(tile) / N) * N;
00098 uint tile_y = (TileY(tile) / N) * N;
00099 uint w = N, h = N;
00100
00101 if (tile_x >= extend * N) {
00102 tile_x -= extend * N;
00103 w += extend * N;
00104 }
00105 if (tile_y >= extend * N) {
00106 tile_y -= extend * N;
00107 h += extend * N;
00108 }
00109 if (tile_x + w < MapSizeX() - extend * N) w += extend * N;
00110 if (tile_y + h < MapSizeY() - extend * N) h += extend * N;
00111
00112 return TileArea(TileXY(tile_x, tile_y), w, h);
00113 }
00114
00119 void Add(TileIndex tile)
00120 {
00121 if (!this->area.Contains(tile)) {
00122 this->AllocateStorage(tile);
00123 }
00124 }
00125
00131 T *Get(TileIndex tile)
00132 {
00133 this->Add(tile);
00134
00135 tile -= this->area.tile;
00136 uint x = TileX(tile) / N;
00137 uint y = TileY(tile) / N;
00138
00139 return &this->data[y * this->area.w / N + x];
00140 }
00141
00143 FORCEINLINE T &operator[](TileIndex tile)
00144 {
00145 return *this->Get(tile);
00146 }
00147 };
00148
00149 #endif