Subversion Repositories public iLand

Rev

Rev 490 | Rev 549 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
1
 
15 Werner 2
#ifndef GRID_H
3
#define GRID_H
4
 
22 Werner 5
#include <QtCore>
15 Werner 6
 
7
 
8
#include <stdexcept>
145 Werner 9
#include <limits>
150 iland 10
#include <cstring>
15 Werner 11
 
373 werner 12
#include "global.h"
13
 
247 werner 14
/** Grid class (template).
15 Werner 15
 
74 Werner 16
Orientation
490 werner 17
The grid is oriented as typically coordinates on the northern hemisphere: higher y-values -> north, higher x-values-> west.
18
The projection is reversed for drawing on screen (Viewport).
74 Werner 19
          N
490 werner 20
  (0/2) (1/2) (2/2)
21
E (0/1) (1/1) (2/1)  W
74 Werner 22
  (0/0) (1/0) (2/0)
23
          S
24
*/
15 Werner 25
template <class T>
26
class Grid {
27
public:
28
 
29
    Grid();
30
    Grid(int cellsize, int sizex, int sizey) { mData=0; setup(cellsize, sizex, sizey); }
58 Werner 31
    Grid(const QRectF rect_metric, const float cellsize) { mData=0; setup(rect_metric,cellsize); }
33 Werner 32
    // copy ctor
33
    Grid(const Grid<T>& toCopy);
105 Werner 34
    ~Grid() { clear(); }
35
    void clear() { if (mData) delete[] mData; mData=0; }
15 Werner 36
 
18 Werner 37
    bool setup(const float cellsize, const int sizex, const int sizey);
22 Werner 38
    bool setup(const QRectF& rect, const double cellsize);
453 werner 39
    bool setup(Grid<T>& source) {     mData = 0;  mRect = source.mRect; return setup(source.cellsize(), source.sizeX(), source.sizeY()); }
75 Werner 40
    void initialize(const T& value) {for( T *p = begin();p!=end(); ++p) *p=value; }
150 iland 41
    void wipe(); ///< write 0-bytes with memcpy to the whole area
154 werner 42
    void wipe(const T value); ///< overwrite the whole area with "value" size of T must be the size of "int" ERRORNOUS!!!
15 Werner 43
 
145 Werner 44
    int sizeX() const { return mSizeX; }
45
    int sizeY() const { return mSizeY; }
46
    float metricSizeX() const { return mSizeX*mCellsize; }
47
    float metricSizeY() const { return mSizeY*mCellsize; }
49 Werner 48
    QRectF metricRect() const { return mRect; }
145 Werner 49
    float cellsize() const { return mCellsize; }
373 werner 50
    int count() const { return mCount; } ///< returns the number of elements of the grid
51
    bool isEmpty() const { return mData==NULL; } ///< returns false if the grid was not setup
32 Werner 52
    // operations
15 Werner 53
    // query
33 Werner 54
    /// access (const) with index variables. use int.
55
    inline const T& operator()(const int ix, const int iy) const { return constValueAtIndex(ix, iy); }
56
    /// access (const) using metric variables. use float.
57
    inline const T& operator()(const float x, const float y) const { return constValueAt(x, y); }
48 Werner 58
    inline const T& operator[] (const QPointF &p) const { return constValueAt(p); }
33 Werner 59
 
77 Werner 60
    inline T& valueAtIndex(const QPoint& pos); ///< value at position defined by indices (x,y)
33 Werner 61
    T& valueAtIndex(const int ix, const int iy) { return valueAtIndex(QPoint(ix,iy)); } ///< const value at position defined by indices (x,y)
285 werner 62
    T& valueAtIndex(const int index) {return mData[index]; } ///< get a ref ot value at (one-dimensional) index 'index'.
33 Werner 63
 
64
    const T& constValueAtIndex(const QPoint& pos) const; ///< value at position defined by a (integer) QPoint
32 Werner 65
    const T& constValueAtIndex(const int ix, const int iy) const { return constValueAtIndex(QPoint(ix,iy)); }
33 Werner 66
 
67
    T& valueAt(const QPointF& posf); ///< value at position defined by metric coordinates (QPointF)
68
    const T& constValueAt(const QPointF& posf) const; ///< value at position defined by metric coordinates (QPointF)
69
 
70
    T& valueAt(const float x, const float y); ///< value at position defined by metric coordinates (x,y)
71
    const T& constValueAt(const float x, const float y) const; ///< value at position defined by metric coordinates (x,y)
72
 
105 Werner 73
    bool coordValid(const float x, const float y) const { return x>=mRect.left() && x<mRect.right()  && y>=mRect.top() && y<mRect.bottom(); }
49 Werner 74
    bool coordValid(const QPointF &pos) const { return coordValid(pos.x(), pos.y()); }
75 Werner 75
 
55 Werner 76
    QPoint indexAt(const QPointF& pos) const { return QPoint(int((pos.x()-mRect.left()) / mCellsize),  int((pos.y()-mRect.top())/mCellsize)); } ///< get index of value at position pos (metric)
538 werner 77
    /// get index (x/y) of the (linear) index 'index' (0..count-1)
78
    QPoint indexOf(const int index) const {return QPoint(index % mSizeX,  index / mSizeX); }
373 werner 79
    bool isIndexValid(const QPoint& pos) const { return (pos.x()>=0 && pos.x()<mSizeX && pos.y()>=0 && pos.y()<mSizeY); } ///< return true, if position is within the grid
80
    bool isIndexValid(const int x, const int y) const {return (x>=0 && x<mSizeX && y>=0 && y<mSizeY); } ///< return true, if index is within the grid
75 Werner 81
    /// force @param pos to contain valid indices with respect to this grid.
55 Werner 82
    void validate(QPoint &pos) const{ pos.setX( qMax(qMin(pos.x(), mSizeX-1), 0) );  pos.setY( qMax(qMin(pos.y(), mSizeY-1), 0) );} ///< ensure that "pos" is a valid key. if out of range, pos is set to minimum/maximum values.
105 Werner 83
    /// get the (metric) centerpoint of cell with index @p pos
84
    QPointF cellCenterPoint(const QPoint &pos) { return QPointF( (pos.x()+0.5)*mCellsize+mRect.left(), (pos.y()+0.5)*mCellsize + mRect.top());} ///< get metric coordinates of the cells center
85
    /// get the metric rectangle of the cell with index @pos
439 werner 86
    QRectF cellRect(const QPoint &pos) const { QRectF r( QPointF(mRect.left() + mCellsize*pos.x(), mRect.top() + pos.y()*mCellsize),
55 Werner 87
                                                   QSizeF(mCellsize, mCellsize)); return r; } ///< return coordinates of rect given by @param pos.
105 Werner 88
 
27 Werner 89
    inline  T* begin() const { return mData; } ///< get "iterator" pointer
37 Werner 90
    inline  T* end() const { return mEnd; } ///< get iterator end-pointer
487 werner 91
    inline QPoint indexOf(T* element) const; ///< retrieve index (x/y) of the pointer element. returns -1/-1 if element is not valid.
27 Werner 92
    // special queries
33 Werner 93
    T max() const; ///< retrieve the maximum value of a grid
94
    T sum() const; ///< retrieve the sum of the grid
95
    T avg() const; ///< retrieve the average value of a grid
391 werner 96
    // modifying operations
97
    void add(const T& summand);
98
    void multiply(const T& factor);
33 Werner 99
    /// creates a grid with lower resolution and averaged cell values.
100
    /// @param factor factor by which grid size is reduced (e.g. 3 -> 3x3=9 pixels are averaged to 1 result pixel)
101
    /// @param offsetx, offsety: start averaging with an offset from 0/0 (e.g.: x=1, y=2, factor=3: -> 1/2-3/4 -> 0/0)
102
    /// @return Grid with size sizeX()/factor x sizeY()/factor
103
    Grid<T> averaged(const int factor, const int offsetx=0, const int offsety=0) const;
104
    /// normalized returns a normalized grid, in a way that the sum()  = @param targetvalue.
105
    /// if the grid is empty or the sum is 0, no modifications are performed.
106
    Grid<T> normalized(const T targetvalue) const;
373 werner 107
    T* ptr(int x, int y) { return &(mData[y*mSizeX + x]); } ///< get a pointer to the element denoted by "x" and "y"
108
    inline double distance(const QPoint &p1, const QPoint &p2); ///< distance (metric) between p1 and p2
109
    const QPoint randomPosition() const; ///< returns a (valid) random position within the grid
15 Werner 110
private:
77 Werner 111
 
15 Werner 112
    T* mData;
37 Werner 113
    T* mEnd; ///< pointer to 1 element behind the last
49 Werner 114
    QRectF mRect;
36 Werner 115
    float mCellsize; ///< size of a cell in meter
116
    int mSizeX; ///< count of cells in x-direction
117
    int mSizeY; ///< count of cells in y-direction
118
    int mCount; ///< total number of cells in the grid
15 Werner 119
};
120
 
121
typedef Grid<float> FloatGrid;
122
 
438 werner 123
/** @class GridRunner is a helper class to iterate over a rectangular fraction of a grid
124
*/
125
template <class T>
126
class GridRunner {
127
public:
439 werner 128
    GridRunner(Grid<T> &target_grid, const QRectF &rectangle) {setup(target_grid, rectangle);}
129
    GridRunner(const Grid<T> &target_grid, const QRectF &rectangle) {setup(target_grid, rectangle);}
438 werner 130
    T* next(); ///< to to next element, return NULL if finished
131
private:
439 werner 132
    void setup(const Grid<T> &target_grid, const QRectF &rectangle);
438 werner 133
    T* mLast;
134
    T* mCurrent;
135
    size_t mLineLength;
136
    size_t mCols;
137
    size_t mCurrentCol;
138
};
139
 
140
 
33 Werner 141
// copy constructor
142
template <class T>
143
Grid<T>::Grid(const Grid<T>& toCopy)
144
{
40 Werner 145
    mData = 0;
50 Werner 146
    mRect = toCopy.mRect;
33 Werner 147
    setup(toCopy.cellsize(), toCopy.sizeX(), toCopy.sizeY());
148
    const T* end = toCopy.end();
149
    T* ptr = begin();
150
    for (T* i= toCopy.begin(); i!=end; ++i, ++ptr)
151
       *ptr = *i;
152
}
22 Werner 153
 
33 Werner 154
// normalize function
32 Werner 155
template <class T>
33 Werner 156
Grid<T> Grid<T>::normalized(const T targetvalue) const
32 Werner 157
{
33 Werner 158
    Grid<T> target(*this);
159
    T total = sum();
160
    T multiplier;
161
    if (total)
162
        multiplier = targetvalue / total;
163
    else
164
        return target;
165
    for (T* p=target.begin();p!=target.end();++p)
166
        *p *= multiplier;
40 Werner 167
    return target;
33 Werner 168
}
169
 
170
 
171
template <class T>
172
Grid<T> Grid<T>::averaged(const int factor, const int offsetx, const int offsety) const
173
{
32 Werner 174
    Grid<T> target;
175
    target.setup(cellsize()*factor, sizeX()/factor, sizeY()/factor);
176
    int x,y;
177
    T sum=0;
178
    target.initialize(sum);
179
    // sum over array of 2x2, 3x3, 4x4, ...
180
    for (x=offsetx;x<mSizeX;x++)
181
        for (y=offsety;y<mSizeY;y++) {
182
            target.valueAtIndex((x-offsetx)/factor, (y-offsety)/factor) += constValueAtIndex(x,y);
183
        }
184
    // divide
185
    double fsquare = factor*factor;
186
    for (T* p=target.begin();p!=target.end();++p)
187
        *p /= fsquare;
188
    return target;
189
}
22 Werner 190
 
15 Werner 191
template <class T>
22 Werner 192
T&  Grid<T>::valueAtIndex(const QPoint& pos)
193
{
75 Werner 194
    //if (isIndexValid(pos)) {
77 Werner 195
        return mData[pos.y()*mSizeX + pos.x()];
75 Werner 196
    //}
197
    //qCritical("Grid::valueAtIndex. invalid: %d/%d", pos.x(), pos.y());
198
    //return mData[0];
22 Werner 199
}
36 Werner 200
 
27 Werner 201
template <class T>
202
const T&  Grid<T>::constValueAtIndex(const QPoint& pos) const
203
{
75 Werner 204
    //if (isIndexValid(pos)) {
77 Werner 205
        return mData[pos.y()*mSizeX + pos.x()];
75 Werner 206
    //}
207
    //qCritical("Grid::constValueAtIndex. invalid: %d/%d", pos.x(), pos.y());
208
    //return mData[0];
27 Werner 209
}
22 Werner 210
 
211
template <class T>
33 Werner 212
T&  Grid<T>::valueAt(const float x, const float y)
213
{
214
    return valueAtIndex( indexAt(QPointF(x,y)) );
215
}
36 Werner 216
 
33 Werner 217
template <class T>
218
const T&  Grid<T>::constValueAt(const float x, const float y) const
219
{
220
    return constValueAtIndex( indexAt(QPointF(x,y)) );
221
}
36 Werner 222
 
33 Werner 223
template <class T>
22 Werner 224
T&  Grid<T>::valueAt(const QPointF& posf)
225
{
226
    return valueAtIndex( indexAt(posf) );
227
}
36 Werner 228
 
33 Werner 229
template <class T>
230
const T&  Grid<T>::constValueAt(const QPointF& posf) const
231
{
232
    return constValueAtIndex( indexAt(posf) );
233
}
22 Werner 234
 
235
template <class T>
15 Werner 236
Grid<T>::Grid()
237
{
37 Werner 238
    mData = 0; mCellsize=0.f;
239
    mEnd = 0;
15 Werner 240
}
241
 
242
template <class T>
18 Werner 243
bool Grid<T>::setup(const float cellsize, const int sizex, const int sizey)
15 Werner 244
{
37 Werner 245
    mSizeX=sizex; mSizeY=sizey; mCellsize=cellsize;
50 Werner 246
    if (mRect.isNull()) // only set rect if not set before
247
        mRect.setCoords(0., 0., cellsize*sizex, cellsize*sizey);
15 Werner 248
    mCount = mSizeX*mSizeY;
37 Werner 249
    if (mData) {
250
         delete[] mData; mData=NULL;
251
     }
15 Werner 252
   if (mCount>0)
37 Werner 253
        mData = new T[mCount];
254
   mEnd = &(mData[mCount]);
15 Werner 255
   return true;
256
}
257
 
258
template <class T>
22 Werner 259
bool Grid<T>::setup(const QRectF& rect, const double cellsize)
15 Werner 260
{
49 Werner 261
    mRect = rect;
22 Werner 262
    int dx = int(rect.width()/cellsize);
49 Werner 263
    if (mRect.left()+cellsize*dx<rect.right())
22 Werner 264
        dx++;
265
    int dy = int(rect.height()/cellsize);
49 Werner 266
    if (mRect.top()+cellsize*dy<rect.bottom())
22 Werner 267
        dy++;
268
    return setup(cellsize, dx, dy);
15 Werner 269
}
270
 
261 werner 271
/** retrieve from the index from an element reversely from a pointer to that element.
272
    The internal memory layout is (for dimx=6, dimy=3):
273
 
274
6  7  8  9  10 11
275
12 13 14 15 16 17
276
Note: north and south are reversed, thus the item with index 0 is located in the south-western edge of the grid! */
487 werner 277
template <class T> inline
27 Werner 278
QPoint Grid<T>::indexOf(T* element) const
25 Werner 279
{
487 werner 280
//    QPoint result(-1,-1);
25 Werner 281
    if (element==NULL || element<mData || element>=end())
487 werner 282
        return QPoint(-1, -1);
25 Werner 283
    int idx = element - mData;
487 werner 284
    return QPoint(idx % mSizeX,  idx / mSizeX);
285
//    result.setX( idx % mSizeX);
286
//    result.setY( idx / mSizeX);
287
//    return result;
25 Werner 288
}
22 Werner 289
 
27 Werner 290
template <class T>
291
T  Grid<T>::max() const
292
{
143 Werner 293
    T maxv = -std::numeric_limits<T>::max();
27 Werner 294
    T* p;
295
    T* pend = end();
296
    for (p=begin(); p!=pend;++p)
297
       maxv = std::max(maxv, *p);
298
    return maxv;
299
}
300
 
33 Werner 301
template <class T>
302
T  Grid<T>::sum() const
303
{
304
    T* pend = end();
305
    T total = 0;
306
    for (T *p=begin(); p!=pend;++p)
307
       total += *p;
308
    return total;
309
}
310
 
311
template <class T>
312
T  Grid<T>::avg() const
313
{
314
    if (count())
315
        return sum() / T(count());
316
    else return 0;
317
}
318
 
150 iland 319
template <class T>
391 werner 320
void Grid<T>::add(const T& summand)
321
{
322
    T* pend = end();
323
    for (T *p=begin(); p!=pend;*p+=summand,++p)
324
       ;
325
}
326
 
327
template <class T>
328
void Grid<T>::multiply(const T& factor)
329
{
330
    T* pend = end();
331
    for (T *p=begin(); p!=pend;*p*=factor,++p)
332
       ;
333
}
334
 
335
 
336
 
337
template <class T>
150 iland 338
void  Grid<T>::wipe()
339
{
340
    memset(mData, 0, mCount*sizeof(T));
341
}
342
template <class T>
343
void  Grid<T>::wipe(const T value)
344
{
154 werner 345
    /* this does not work properly !!! */
153 werner 346
    if (sizeof(T)==sizeof(int)) {
347
        float temp = value;
348
        float *pf = &temp;
349
 
350
        memset(mData, *((int*)pf), mCount*sizeof(T));
351
    } else
150 iland 352
        initialize(value);
353
}
354
 
373 werner 355
template <class T>
356
double Grid<T>::distance(const QPoint &p1, const QPoint &p2)
357
{
358
    QPointF fp1=cellCenterPoint(p1);
359
    QPointF fp2=cellCenterPoint(p2);
360
    double distance = sqrt( (fp1.x()-fp2.x())*(fp1.x()-fp2.x()) + (fp1.y()-fp2.y())*(fp1.y()-fp2.y()));
361
    return distance;
362
}
363
 
364
template <class T>
365
const QPoint Grid<T>::randomPosition() const
366
{
367
    return QPoint(irandom(0,mSizeX-1), irandom(0, mSizeY-1));
368
}
438 werner 369
 
373 werner 370
////////////////////////////////////////////////////////////
438 werner 371
// grid runner
372
////////////////////////////////////////////////////////////
373
template <class T>
439 werner 374
void GridRunner<T>::setup(const Grid<T> &target_grid, const QRectF &rectangle)
438 werner 375
{
376
    QPoint upper_left = target_grid.indexAt(rectangle.topLeft());
377
    QPoint lower_right = target_grid.indexAt(rectangle.bottomRight());
439 werner 378
    mCurrent = const_cast<Grid<T> &>(target_grid).ptr(upper_left.x(), upper_left.y());
379
    mLast = const_cast<Grid<T> &>(target_grid).ptr(lower_right.x()-1, lower_right.y()-1);
438 werner 380
    mCols = lower_right.x() - upper_left.x(); //
381
    mLineLength =  target_grid.sizeX() - mCols;
382
    mCurrentCol = 0;
383
}
384
 
385
template <class T>
386
T* GridRunner<T>::next()
387
{
388
    if (mCurrent>mLast)
389
        return NULL;
390
    T* t = mCurrent;
391
    mCurrent++;
392
    mCurrentCol++;
393
    if (mCurrentCol >= mCols) {
394
        mCurrent += mLineLength; // skip to next line
395
        mCurrentCol = 0;
396
    }
397
    return t;
398
}
399
 
400
////////////////////////////////////////////////////////////
36 Werner 401
// global functions
373 werner 402
////////////////////////////////////////////////////////////
36 Werner 403
 
404
/// dumps a FloatGrid to a String.
46 Werner 405
/// rows will be y-lines, columns x-values. (see grid.cpp)
36 Werner 406
QString gridToString(const FloatGrid &grid);
407
 
408
/// creates and return a QImage from Grid-Data.
409
/// @param black_white true: max_value = white, min_value = black, false: color-mode: uses a HSV-color model from blue (min_value) to red (max_value), default: color mode (false)
410
/// @param min_value, max_value min/max bounds for color calcuations. values outside bounds are limited to these values. defaults: min=0, max=1
411
/// @param reverse if true, color ramps are inversed (to: min_value = white (black and white mode) or red (color mode). default = false.
412
/// @return a QImage with the Grids size of pixels. Pixel coordinates relate to the index values of the grid.
413
QImage gridToImage(const FloatGrid &grid,
414
                   bool black_white=false,
415
                   double min_value=0., double max_value=1.,
416
                   bool reverse=false);
417
 
285 werner 418
/** load into 'rGrid' the content of the image pointed at by 'fileName'.
419
    Pixels are converted to grey-scale and then transformend to a value ranging from 0..1 (black..white).
420
  */
421
bool loadGridFromImage(const QString &fileName, FloatGrid &rGrid);
422
 
46 Werner 423
/// template version for non-float grids (see also version for FloatGrid)
36 Werner 424
template <class T>
46 Werner 425
        QString gridToString(const Grid<T> &grid)
36 Werner 426
{
427
    QString res;
428
    QTextStream ts(&res);
429
 
46 Werner 430
    for (int y=0;y<grid.sizeY();y++){
431
        for (int x=0;x<grid.sizeX();x++){
36 Werner 432
            ts << grid.constValueAtIndex(x,y) << ";";
433
        }
434
        ts << "\r\n";
435
    }
436
 
437
    return res;
438
}
46 Werner 439
 
15 Werner 440
#endif // GRID_H