Subversion Repositories public iLand

Rev

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

Rev Author Line No. Line
1
 
671 werner 2
/********************************************************************************************
3
**    iLand - an individual based forest landscape and disturbance model
4
**    http://iland.boku.ac.at
5
**    Copyright (C) 2009-  Werner Rammer, Rupert Seidl
6
**
7
**    This program is free software: you can redistribute it and/or modify
8
**    it under the terms of the GNU General Public License as published by
9
**    the Free Software Foundation, either version 3 of the License, or
10
**    (at your option) any later version.
11
**
12
**    This program is distributed in the hope that it will be useful,
13
**    but WITHOUT ANY WARRANTY; without even the implied warranty of
14
**    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15
**    GNU General Public License for more details.
16
**
17
**    You should have received a copy of the GNU General Public License
18
**    along with this program.  If not, see <http://www.gnu.org/licenses/>.
19
********************************************************************************************/
20
 
15 Werner 21
#ifndef GRID_H
22
#define GRID_H
23
 
22 Werner 24
#include <QtCore>
15 Werner 25
 
26
 
27
#include <stdexcept>
145 Werner 28
#include <limits>
150 iland 29
#include <cstring>
15 Werner 30
 
373 werner 31
#include "global.h"
32
 
247 werner 33
/** Grid class (template).
697 werner 34
@ingroup tools
74 Werner 35
Orientation
656 werner 36
The grid is oriented as typically coordinates on the northern hemisphere: higher y-values -> north, higher x-values-> east.
490 werner 37
The projection is reversed for drawing on screen (Viewport).
74 Werner 38
          N
490 werner 39
  (0/2) (1/2) (2/2)
656 werner 40
W (0/1) (1/1) (2/1)  E
74 Werner 41
  (0/0) (1/0) (2/0)
42
          S
43
*/
15 Werner 44
template <class T>
45
class Grid {
46
public:
47
 
48
    Grid();
49
    Grid(int cellsize, int sizex, int sizey) { mData=0; setup(cellsize, sizex, sizey); }
914 werner 50
    /// create from a metric rect
58 Werner 51
    Grid(const QRectF rect_metric, const float cellsize) { mData=0; setup(rect_metric,cellsize); }
33 Werner 52
    // copy ctor
53
    Grid(const Grid<T>& toCopy);
105 Werner 54
    ~Grid() { clear(); }
55
    void clear() { if (mData) delete[] mData; mData=0; }
15 Werner 56
 
18 Werner 57
    bool setup(const float cellsize, const int sizex, const int sizey);
22 Werner 58
    bool setup(const QRectF& rect, const double cellsize);
896 werner 59
    bool setup(const Grid<T>& source) { clear();  mRect = source.mRect; return setup(source.mRect, source.mCellsize); }
75 Werner 60
    void initialize(const T& value) {for( T *p = begin();p!=end(); ++p) *p=value; }
150 iland 61
    void wipe(); ///< write 0-bytes with memcpy to the whole area
154 werner 62
    void wipe(const T value); ///< overwrite the whole area with "value" size of T must be the size of "int" ERRORNOUS!!!
764 werner 63
    /// copies the content of the source grid to this grid.
64
    /// no operation, if the grids are not of the same size.
65
    void copy(const Grid<T> source) { if (source.count()==count()) memcpy(mData, source.mData, count()*sizeof(T)); }
15 Werner 66
 
797 werner 67
    // get the number of cells in x and y direction
145 Werner 68
    int sizeX() const { return mSizeX; }
69
    int sizeY() const { return mSizeY; }
797 werner 70
    // get the size of the grid in metric coordinates (x and y direction)
145 Werner 71
    float metricSizeX() const { return mSizeX*mCellsize; }
72
    float metricSizeY() const { return mSizeY*mCellsize; }
797 werner 73
    /// get the metric rectangle of the grid
49 Werner 74
    QRectF metricRect() const { return mRect; }
797 werner 75
    /// get the rectangle of the grid in terms of indices
76
    QRect rectangle() const { return QRect(QPoint(0,0), QPoint(sizeX(), sizeY())); }
77
    /// get the length of one pixel of the grid
145 Werner 78
    float cellsize() const { return mCellsize; }
373 werner 79
    int count() const { return mCount; } ///< returns the number of elements of the grid
80
    bool isEmpty() const { return mData==NULL; } ///< returns false if the grid was not setup
32 Werner 81
    // operations
15 Werner 82
    // query
33 Werner 83
    /// access (const) with index variables. use int.
84
    inline const T& operator()(const int ix, const int iy) const { return constValueAtIndex(ix, iy); }
85
    /// access (const) using metric variables. use float.
86
    inline const T& operator()(const float x, const float y) const { return constValueAt(x, y); }
1067 werner 87
    /// access value of grid with a QPoint
88
    inline const T& operator[](const QPoint &p) const { return constValueAtIndex(p); }
89
    /// use the square brackets to access by index
90
    inline T& operator[](const int idx) const { return mData[idx]; }
91
    /// use the square bracket to access by QPointF
92
    inline T& operator[] (const QPointF &p) const { return valueAt(p); }
33 Werner 93
 
705 werner 94
    inline T& valueAtIndex(const QPoint& pos) {return valueAtIndex(pos.x(), pos.y());}  ///< value at position defined by a QPoint defining the two indices (x,y)
95
    T& valueAtIndex(const int ix, const int iy) { return mData[iy*mSizeX + ix];  } ///< const value at position defined by indices (x,y)
285 werner 96
    T& valueAtIndex(const int index) {return mData[index]; } ///< get a ref ot value at (one-dimensional) index 'index'.
33 Werner 97
 
705 werner 98
    /// value at position defined by a (integer) QPoint
99
    inline const T& constValueAtIndex(const QPoint& pos) const {return constValueAtIndex(pos.x(), pos.y()); }
100
    /// value at position defined by a pair of integer coordinates
101
    inline const T& constValueAtIndex(const int ix, const int iy) const { return mData[iy*mSizeX + ix];  }
102
    /// value at position defined by the index within the grid
549 werner 103
    const T& constValueAtIndex(const int index) const {return mData[index]; } ///< get a ref ot value at (one-dimensional) index 'index'.
33 Werner 104
 
105
    T& valueAt(const QPointF& posf); ///< value at position defined by metric coordinates (QPointF)
106
    const T& constValueAt(const QPointF& posf) const; ///< value at position defined by metric coordinates (QPointF)
107
 
108
    T& valueAt(const float x, const float y); ///< value at position defined by metric coordinates (x,y)
109
    const T& constValueAt(const float x, const float y) const; ///< value at position defined by metric coordinates (x,y)
110
 
1067 werner 111
 
105 Werner 112
    bool coordValid(const float x, const float y) const { return x>=mRect.left() && x<mRect.right()  && y>=mRect.top() && y<mRect.bottom(); }
49 Werner 113
    bool coordValid(const QPointF &pos) const { return coordValid(pos.x(), pos.y()); }
75 Werner 114
 
55 Werner 115
    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 116
    /// get index (x/y) of the (linear) index 'index' (0..count-1)
117
    QPoint indexOf(const int index) const {return QPoint(index % mSizeX,  index / mSizeX); }
373 werner 118
    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
119
    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
1068 werner 120
 
121
    /// returns the index of an aligned grid (with the same size and matching origin) with the double cell size (e.g. to scale from a 10m grid to a 20m grid)
122
    int index2(int idx) const {return ((idx/mSizeX)/2)*mSizeX/2 + (idx%mSizeX)/2; }
123
    /// returns the index of an aligned grid (the same size) with the 5 times bigger cells (e.g. to scale from a 2m grid to a 10m grid)
124
    int index5(int idx) const {return ((idx/mSizeX)/5)*mSizeX/5 + (idx%mSizeX)/5; }
125
 
75 Werner 126
    /// force @param pos to contain valid indices with respect to this grid.
55 Werner 127
    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 128
    /// get the (metric) centerpoint of cell with index @p pos
549 werner 129
    QPointF cellCenterPoint(const QPoint &pos) const { return QPointF( (pos.x()+0.5)*mCellsize+mRect.left(), (pos.y()+0.5)*mCellsize + mRect.top());} ///< get metric coordinates of the cells center
881 werner 130
    /// get the metric cell center point of the cell given by index 'index'
131
    QPointF cellCenterPoint(const int &index) const { QPoint pos=indexOf(index); return QPointF( (pos.x()+0.5)*mCellsize+mRect.left(), (pos.y()+0.5)*mCellsize + mRect.top());}
105 Werner 132
    /// get the metric rectangle of the cell with index @pos
439 werner 133
    QRectF cellRect(const QPoint &pos) const { QRectF r( QPointF(mRect.left() + mCellsize*pos.x(), mRect.top() + pos.y()*mCellsize),
55 Werner 134
                                                   QSizeF(mCellsize, mCellsize)); return r; } ///< return coordinates of rect given by @param pos.
105 Werner 135
 
27 Werner 136
    inline  T* begin() const { return mData; } ///< get "iterator" pointer
37 Werner 137
    inline  T* end() const { return mEnd; } ///< get iterator end-pointer
717 werner 138
    inline QPoint indexOf(const T* element) const; ///< retrieve index (x/y) of the pointer element. returns -1/-1 if element is not valid.
27 Werner 139
    // special queries
33 Werner 140
    T max() const; ///< retrieve the maximum value of a grid
141
    T sum() const; ///< retrieve the sum of the grid
142
    T avg() const; ///< retrieve the average value of a grid
391 werner 143
    // modifying operations
144
    void add(const T& summand);
145
    void multiply(const T& factor);
33 Werner 146
    /// creates a grid with lower resolution and averaged cell values.
147
    /// @param factor factor by which grid size is reduced (e.g. 3 -> 3x3=9 pixels are averaged to 1 result pixel)
148
    /// @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)
149
    /// @return Grid with size sizeX()/factor x sizeY()/factor
150
    Grid<T> averaged(const int factor, const int offsetx=0, const int offsety=0) const;
151
    /// normalized returns a normalized grid, in a way that the sum()  = @param targetvalue.
152
    /// if the grid is empty or the sum is 0, no modifications are performed.
153
    Grid<T> normalized(const T targetvalue) const;
1010 werner 154
    T* ptr(int x, int y) { return &(mData[y*mSizeX + x]); } ///< get a pointer to the element indexed by "x" and "y"
373 werner 155
    inline double distance(const QPoint &p1, const QPoint &p2); ///< distance (metric) between p1 and p2
156
    const QPoint randomPosition() const; ///< returns a (valid) random position within the grid
15 Werner 157
private:
77 Werner 158
 
15 Werner 159
    T* mData;
37 Werner 160
    T* mEnd; ///< pointer to 1 element behind the last
49 Werner 161
    QRectF mRect;
36 Werner 162
    float mCellsize; ///< size of a cell in meter
163
    int mSizeX; ///< count of cells in x-direction
164
    int mSizeY; ///< count of cells in y-direction
165
    int mCount; ///< total number of cells in the grid
15 Werner 166
};
167
 
1067 werner 168
 
15 Werner 169
typedef Grid<float> FloatGrid;
170
 
1008 werner 171
enum GridViewType { GridViewRainbow=0, GridViewRainbowReverse=1, GridViewGray=2, GridViewGrayReverse=3, GridViewHeat=4,
1040 werner 172
                    GridViewGreens=5, GridViewReds=6, GridViewBlues=7,
880 werner 173
                    GridViewBrewerDiv=10, GridViewBrewerQual=11, GridViewTerrain=12, GridViewCustom=14  };
643 werner 174
 
438 werner 175
/** @class GridRunner is a helper class to iterate over a rectangular fraction of a grid
176
*/
177
template <class T>
178
class GridRunner {
179
public:
650 werner 180
    // constructors with a QRectF (metric coordinates)
617 werner 181
    GridRunner(Grid<T> &target_grid, const QRectF &rectangle) {setup(&target_grid, rectangle);}
182
    GridRunner(const Grid<T> &target_grid, const QRectF &rectangle) {setup(&target_grid, rectangle);}
183
    GridRunner(Grid<T> *target_grid, const QRectF &rectangle) {setup(target_grid, rectangle);}
650 werner 184
    // constructors with a QRect (indices within the grid)
185
    GridRunner(Grid<T> &target_grid, const QRect &rectangle) {setup(&target_grid, rectangle);}
186
    GridRunner(const Grid<T> &target_grid, const QRect &rectangle) {setup(&target_grid, rectangle);}
187
    GridRunner(Grid<T> *target_grid, const QRect &rectangle) {setup(target_grid, rectangle);}
914 werner 188
    GridRunner(Grid<T> *target_grid) {setup(target_grid, target_grid->rectangle()); }
438 werner 189
    T* next(); ///< to to next element, return NULL if finished
662 werner 190
    T* current() const { return mCurrent; }
1010 werner 191
    bool isValid() const {return mCurrent>=mFirst && mCurrent<=mLast; }
902 werner 192
    /// return the (index) - coordinates of the current position in the grid
193
    QPoint currentIndex() const { return mGrid->indexOf(mCurrent); }
194
    /// return the coordinates of the cell center point of the current position in the grid.
195
    QPointF currentCoord() const {return mGrid->cellCenterPoint(mGrid->indexOf(mCurrent));}
650 werner 196
    void reset() { mCurrent = mFirst-1; mCurrentCol = -1; }
1010 werner 197
    /// set the internal pointer to the pixel at index 'new_index'. The index is relative to the base grid!
198
    void setPosition(QPoint new_index) { if (mGrid->isIndexValid(new_index)) mCurrent = const_cast<Grid<T> *>(mGrid)->ptr(new_index.x(), new_index.y()); else mCurrent=0; }
650 werner 199
    // helpers
200
    /// fill array with pointers to neighbors (north, east, west, south)
201
    /// or Null-pointers if out of range.
202
    /// the target array (rArray) is not checked and must be valid!
203
    void neighbors4(T** rArray);
204
    void neighbors8(T** rArray);
438 werner 205
private:
617 werner 206
    void setup(const Grid<T> *target_grid, const QRectF &rectangle);
650 werner 207
    void setup(const Grid<T> *target_grid, const QRect &rectangle);
902 werner 208
    const Grid<T> *mGrid;
650 werner 209
    T* mFirst; // points to the first element of the grid
210
    T* mLast; // points to the last element of the grid
438 werner 211
    T* mCurrent;
212
    size_t mLineLength;
213
    size_t mCols;
984 werner 214
    int mCurrentCol;
438 werner 215
};
216
 
646 werner 217
/** @class Vector3D is a simple 3d vector.
218
  QVector3D (from Qt) is in QtGui so we needed a replacement.
219
*/
220
class Vector3D
221
{
222
 public:
223
    Vector3D(): mX(0.), mY(0.), mZ(0.) {}
224
    Vector3D(const double x, const double y, const double z): mX(x), mY(y), mZ(z) {}
225
    double x() const { return mX; } ///< get x-coordinate
226
    double y() const { return mY; } ///< get y-coordinate
227
    double z() const { return mZ; } ///< get z-coordinate
228
    // set variables
229
    void setX(const double x) { mX=x; } ///< set value of the x-coordinate
230
    void setY(const double y) { mY=y; } ///< set value of the y-coordinate
231
    void setZ(const double z) { mZ=z; } ///< set value of the z-coordinate
232
private:
233
    double mX;
234
    double mY;
235
    double mZ;
236
};
438 werner 237
 
33 Werner 238
// copy constructor
239
template <class T>
240
Grid<T>::Grid(const Grid<T>& toCopy)
241
{
40 Werner 242
    mData = 0;
50 Werner 243
    mRect = toCopy.mRect;
33 Werner 244
    setup(toCopy.cellsize(), toCopy.sizeX(), toCopy.sizeY());
245
    const T* end = toCopy.end();
246
    T* ptr = begin();
247
    for (T* i= toCopy.begin(); i!=end; ++i, ++ptr)
248
       *ptr = *i;
249
}
22 Werner 250
 
33 Werner 251
// normalize function
32 Werner 252
template <class T>
33 Werner 253
Grid<T> Grid<T>::normalized(const T targetvalue) const
32 Werner 254
{
33 Werner 255
    Grid<T> target(*this);
256
    T total = sum();
257
    T multiplier;
258
    if (total)
259
        multiplier = targetvalue / total;
260
    else
261
        return target;
262
    for (T* p=target.begin();p!=target.end();++p)
263
        *p *= multiplier;
40 Werner 264
    return target;
33 Werner 265
}
266
 
267
 
268
template <class T>
269
Grid<T> Grid<T>::averaged(const int factor, const int offsetx, const int offsety) const
270
{
32 Werner 271
    Grid<T> target;
272
    target.setup(cellsize()*factor, sizeX()/factor, sizeY()/factor);
273
    int x,y;
274
    T sum=0;
275
    target.initialize(sum);
276
    // sum over array of 2x2, 3x3, 4x4, ...
277
    for (x=offsetx;x<mSizeX;x++)
278
        for (y=offsety;y<mSizeY;y++) {
279
            target.valueAtIndex((x-offsetx)/factor, (y-offsety)/factor) += constValueAtIndex(x,y);
280
        }
281
    // divide
282
    double fsquare = factor*factor;
283
    for (T* p=target.begin();p!=target.end();++p)
284
        *p /= fsquare;
285
    return target;
286
}
22 Werner 287
 
36 Werner 288
 
27 Werner 289
template <class T>
33 Werner 290
T&  Grid<T>::valueAt(const float x, const float y)
291
{
292
    return valueAtIndex( indexAt(QPointF(x,y)) );
293
}
36 Werner 294
 
33 Werner 295
template <class T>
296
const T&  Grid<T>::constValueAt(const float x, const float y) const
297
{
298
    return constValueAtIndex( indexAt(QPointF(x,y)) );
299
}
36 Werner 300
 
33 Werner 301
template <class T>
22 Werner 302
T&  Grid<T>::valueAt(const QPointF& posf)
303
{
304
    return valueAtIndex( indexAt(posf) );
305
}
36 Werner 306
 
33 Werner 307
template <class T>
308
const T&  Grid<T>::constValueAt(const QPointF& posf) const
309
{
310
    return constValueAtIndex( indexAt(posf) );
311
}
22 Werner 312
 
313
template <class T>
15 Werner 314
Grid<T>::Grid()
315
{
37 Werner 316
    mData = 0; mCellsize=0.f;
317
    mEnd = 0;
912 werner 318
    mSizeX=0; mSizeY=0; mCount=0;
15 Werner 319
}
320
 
321
template <class T>
18 Werner 322
bool Grid<T>::setup(const float cellsize, const int sizex, const int sizey)
15 Werner 323
{
912 werner 324
    mSizeX=sizex; mSizeY=sizey;
951 werner 325
    if (mRect.isNull()) // only set rect if not set before (e.g. by call to setup(QRectF, double))
50 Werner 326
        mRect.setCoords(0., 0., cellsize*sizex, cellsize*sizey);
912 werner 327
 
328
    if (mData) {
329
        // test if we can re-use the allocated memory.
951 werner 330
        if (mSizeX*mSizeY > mCount || mCellsize != cellsize) {
912 werner 331
            // we cannot re-use the memory - create new data
332
            delete[] mData; mData=NULL;
333
        }
334
    }
335
    mCellsize=cellsize;
15 Werner 336
    mCount = mSizeX*mSizeY;
951 werner 337
    if (mCount==0)
338
        return false;
339
    if (mData==NULL)
37 Werner 340
        mData = new T[mCount];
912 werner 341
    mEnd = &(mData[mCount]);
342
    return true;
15 Werner 343
}
344
 
345
template <class T>
22 Werner 346
bool Grid<T>::setup(const QRectF& rect, const double cellsize)
15 Werner 347
{
49 Werner 348
    mRect = rect;
22 Werner 349
    int dx = int(rect.width()/cellsize);
49 Werner 350
    if (mRect.left()+cellsize*dx<rect.right())
22 Werner 351
        dx++;
352
    int dy = int(rect.height()/cellsize);
49 Werner 353
    if (mRect.top()+cellsize*dy<rect.bottom())
22 Werner 354
        dy++;
355
    return setup(cellsize, dx, dy);
15 Werner 356
}
357
 
261 werner 358
/** retrieve from the index from an element reversely from a pointer to that element.
359
    The internal memory layout is (for dimx=6, dimy=3):
360
 
361
6  7  8  9  10 11
362
12 13 14 15 16 17
363
Note: north and south are reversed, thus the item with index 0 is located in the south-western edge of the grid! */
487 werner 364
template <class T> inline
717 werner 365
QPoint Grid<T>::indexOf(const T* element) const
25 Werner 366
{
487 werner 367
//    QPoint result(-1,-1);
25 Werner 368
    if (element==NULL || element<mData || element>=end())
487 werner 369
        return QPoint(-1, -1);
25 Werner 370
    int idx = element - mData;
487 werner 371
    return QPoint(idx % mSizeX,  idx / mSizeX);
372
//    result.setX( idx % mSizeX);
373
//    result.setY( idx / mSizeX);
374
//    return result;
25 Werner 375
}
22 Werner 376
 
27 Werner 377
template <class T>
378
T  Grid<T>::max() const
379
{
143 Werner 380
    T maxv = -std::numeric_limits<T>::max();
27 Werner 381
    T* p;
382
    T* pend = end();
383
    for (p=begin(); p!=pend;++p)
384
       maxv = std::max(maxv, *p);
385
    return maxv;
386
}
387
 
33 Werner 388
template <class T>
389
T  Grid<T>::sum() const
390
{
391
    T* pend = end();
392
    T total = 0;
393
    for (T *p=begin(); p!=pend;++p)
394
       total += *p;
395
    return total;
396
}
397
 
398
template <class T>
399
T  Grid<T>::avg() const
400
{
401
    if (count())
402
        return sum() / T(count());
403
    else return 0;
404
}
405
 
150 iland 406
template <class T>
391 werner 407
void Grid<T>::add(const T& summand)
408
{
409
    T* pend = end();
410
    for (T *p=begin(); p!=pend;*p+=summand,++p)
411
       ;
412
}
413
 
414
template <class T>
415
void Grid<T>::multiply(const T& factor)
416
{
417
    T* pend = end();
418
    for (T *p=begin(); p!=pend;*p*=factor,++p)
419
       ;
420
}
421
 
422
 
423
 
424
template <class T>
150 iland 425
void  Grid<T>::wipe()
426
{
427
    memset(mData, 0, mCount*sizeof(T));
428
}
429
template <class T>
430
void  Grid<T>::wipe(const T value)
431
{
154 werner 432
    /* this does not work properly !!! */
153 werner 433
    if (sizeof(T)==sizeof(int)) {
434
        float temp = value;
435
        float *pf = &temp;
436
 
437
        memset(mData, *((int*)pf), mCount*sizeof(T));
438
    } else
150 iland 439
        initialize(value);
440
}
441
 
373 werner 442
template <class T>
443
double Grid<T>::distance(const QPoint &p1, const QPoint &p2)
444
{
445
    QPointF fp1=cellCenterPoint(p1);
446
    QPointF fp2=cellCenterPoint(p2);
447
    double distance = sqrt( (fp1.x()-fp2.x())*(fp1.x()-fp2.x()) + (fp1.y()-fp2.y())*(fp1.y()-fp2.y()));
448
    return distance;
449
}
450
 
451
template <class T>
452
const QPoint Grid<T>::randomPosition() const
453
{
454
    return QPoint(irandom(0,mSizeX-1), irandom(0, mSizeY-1));
455
}
438 werner 456
 
373 werner 457
////////////////////////////////////////////////////////////
438 werner 458
// grid runner
459
////////////////////////////////////////////////////////////
460
template <class T>
650 werner 461
void GridRunner<T>::setup(const Grid<T> *target_grid, const QRect &rectangle)
438 werner 462
{
650 werner 463
    QPoint upper_left = rectangle.topLeft();
651 werner 464
    // due to the strange behavior of QRect::bottom() and right():
650 werner 465
    QPoint lower_right = rectangle.bottomRight();
617 werner 466
    mCurrent = const_cast<Grid<T> *>(target_grid)->ptr(upper_left.x(), upper_left.y());
650 werner 467
    mFirst = mCurrent;
585 werner 468
    mCurrent--; // point to first element -1
617 werner 469
    mLast = const_cast<Grid<T> *>(target_grid)->ptr(lower_right.x()-1, lower_right.y()-1);
438 werner 470
    mCols = lower_right.x() - upper_left.x(); //
617 werner 471
    mLineLength =  target_grid->sizeX() - mCols;
585 werner 472
    mCurrentCol = -1;
902 werner 473
    mGrid = target_grid;
585 werner 474
//    qDebug() << "GridRunner: rectangle:" << rectangle
475
//             << "upper_left:" << target_grid.cellCenterPoint(target_grid.indexOf(mCurrent))
476
//             << "lower_right:" << target_grid.cellCenterPoint(target_grid.indexOf(mLast));
438 werner 477
}
478
 
479
template <class T>
650 werner 480
void GridRunner<T>::setup(const Grid<T> *target_grid, const QRectF &rectangle_metric)
481
{
482
    QRect rect(target_grid->indexAt(rectangle_metric.topLeft()),
483
               target_grid->indexAt(rectangle_metric.bottomRight()) );
484
    setup (target_grid, rect);
485
}
486
 
487
template <class T>
438 werner 488
T* GridRunner<T>::next()
489
{
490
    if (mCurrent>mLast)
491
        return NULL;
492
    mCurrent++;
493
    mCurrentCol++;
585 werner 494
 
1031 werner 495
    if (mCurrentCol >= int(mCols)) {
438 werner 496
        mCurrent += mLineLength; // skip to next line
497
        mCurrentCol = 0;
498
    }
585 werner 499
    if (mCurrent>mLast)
500
        return NULL;
501
    else
502
        return mCurrent;
438 werner 503
}
504
 
650 werner 505
template <class T>
656 werner 506
/// get pointers the the 4-neighborhood
1037 werner 507
/// north, east, west, south
803 werner 508
/// 0-pointers are returned for edge pixels.
650 werner 509
void GridRunner<T>::neighbors4(T** rArray)
510
{
511
    // north:
651 werner 512
    rArray[0] = mCurrent + mCols + mLineLength > mLast?0: mCurrent + mCols + mLineLength;
650 werner 513
    // south:
651 werner 514
    rArray[3] = mCurrent - (mCols + mLineLength) < mFirst?0: mCurrent -  (mCols + mLineLength);
650 werner 515
    // east / west
1031 werner 516
    rArray[1] = mCurrentCol<int(mCols)? mCurrent + 1 : 0;
656 werner 517
    rArray[2] = mCurrentCol>0? mCurrent-1 : 0;
650 werner 518
}
519
 
520
/// get pointers to the 8-neighbor-hood
521
/// north/east/west/south/NE/NW/SE/SW
803 werner 522
/// 0-pointers are returned for edge pixels.
650 werner 523
template <class T>
524
void GridRunner<T>::neighbors8(T** rArray)
525
{
526
    neighbors4(rArray);
527
    // north-east
656 werner 528
    rArray[4] = rArray[0] && rArray[1]? rArray[0]+1: 0;
650 werner 529
    // north-west
656 werner 530
    rArray[5] = rArray[0] && rArray[2]? rArray[0]-1: 0;
650 werner 531
    // south-east
656 werner 532
    rArray[6] = rArray[3] && rArray[1]? rArray[3]+1: 0;
650 werner 533
    // south-west
656 werner 534
    rArray[7] = rArray[3] && rArray[2]? rArray[3]-1: 0;
650 werner 535
 
536
}
537
 
438 werner 538
////////////////////////////////////////////////////////////
36 Werner 539
// global functions
373 werner 540
////////////////////////////////////////////////////////////
36 Werner 541
 
542
/// dumps a FloatGrid to a String.
46 Werner 543
/// rows will be y-lines, columns x-values. (see grid.cpp)
599 werner 544
QString gridToString(const FloatGrid &grid, const QChar sep=QChar(';'), const int newline_after=-1);
36 Werner 545
 
546
/// creates and return a QImage from Grid-Data.
547
/// @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)
548
/// @param min_value, max_value min/max bounds for color calcuations. values outside bounds are limited to these values. defaults: min=0, max=1
549
/// @param reverse if true, color ramps are inversed (to: min_value = white (black and white mode) or red (color mode). default = false.
550
/// @return a QImage with the Grids size of pixels. Pixel coordinates relate to the index values of the grid.
551
QImage gridToImage(const FloatGrid &grid,
552
                   bool black_white=false,
553
                   double min_value=0., double max_value=1.,
554
                   bool reverse=false);
555
 
556 werner 556
 
285 werner 557
/** load into 'rGrid' the content of the image pointed at by 'fileName'.
558
    Pixels are converted to grey-scale and then transformend to a value ranging from 0..1 (black..white).
559
  */
560
bool loadGridFromImage(const QString &fileName, FloatGrid &rGrid);
561
 
46 Werner 562
/// template version for non-float grids (see also version for FloatGrid)
599 werner 563
/// @param sep string separator
564
/// @param newline_after if <>-1 a newline is added after every 'newline_after' data values
36 Werner 565
template <class T>
599 werner 566
        QString gridToString(const Grid<T> &grid, const QChar sep=QChar(';'), const int newline_after=-1)
36 Werner 567
{
568
    QString res;
569
    QTextStream ts(&res);
570
 
599 werner 571
    int newl_counter = newline_after;
708 werner 572
    for (int y=grid.sizeY()-1;y>=0;--y){
46 Werner 573
        for (int x=0;x<grid.sizeX();x++){
599 werner 574
            ts << grid.constValueAtIndex(x,y) << sep;
575
            if (--newl_counter==0) {
576
                ts << "\r\n";
577
                newl_counter = newline_after;
578
            }
36 Werner 579
        }
580
        ts << "\r\n";
581
    }
582
 
583
    return res;
584
}
46 Werner 585
 
599 werner 586
/// template version for non-float grids (see also version for FloatGrid)
587
/// @param valueFunction pointer to a function with the signature: QString func(const T&) : this should return a QString
588
/// @param sep string separator
589
/// @param newline_after if <>-1 a newline is added after every 'newline_after' data values
590
template <class T>
591
        QString gridToString(const Grid<T> &grid, QString (*valueFunction)(const T& value), const QChar sep=QChar(';'), const int newline_after=-1 )
708 werner 592
        {
593
            QString res;
594
            QTextStream ts(&res);
599 werner 595
 
708 werner 596
            int newl_counter = newline_after;
597
            for (int y=grid.sizeY()-1;y>=0;--y){
598
                for (int x=0;x<grid.sizeX();x++){
599
                    ts << (*valueFunction)(grid.constValueAtIndex(x,y)) << sep;
599 werner 600
 
708 werner 601
                    if (--newl_counter==0) {
602
                        ts << "\r\n";
603
                        newl_counter = newline_after;
604
                    }
605
                }
599 werner 606
                ts << "\r\n";
607
            }
708 werner 608
 
609
            return res;
599 werner 610
        }
646 werner 611
void modelToWorld(const Vector3D &From, Vector3D &To);
599 werner 612
 
613
template <class T>
614
    QString gridToESRIRaster(const Grid<T> &grid, QString (*valueFunction)(const T& value) )
615
{
646 werner 616
        Vector3D model(grid.metricRect().left(), grid.metricRect().top(), 0.);
617
        Vector3D world;
599 werner 618
        modelToWorld(model, world);
607 werner 619
        QString result = QString("ncols %1\r\nnrows %2\r\nxllcorner %3\r\nyllcorner %4\r\ncellsize %5\r\nNODATA_value %6\r\n")
599 werner 620
                                .arg(grid.sizeX())
621
                                .arg(grid.sizeY())
600 werner 622
                                .arg(world.x(),0,'f').arg(world.y(),0,'f')
599 werner 623
                                .arg(grid.cellsize()).arg(-9999);
694 werner 624
        QString line =  gridToString(grid, valueFunction, QChar(' ')); // for special grids
625
        return result + line;
626
}
599 werner 627
 
628
    template <class T>
629
        QString gridToESRIRaster(const Grid<T> &grid )
630
{
646 werner 631
            Vector3D model(grid.metricRect().left(), grid.metricRect().top(), 0.);
632
            Vector3D world;
599 werner 633
            modelToWorld(model, world);
683 werner 634
            QString result = QString("ncols %1\r\nnrows %2\r\nxllcorner %3\r\nyllcorner %4\r\ncellsize %5\r\nNODATA_value %6\r\n")
599 werner 635
                    .arg(grid.sizeX())
636
                    .arg(grid.sizeY())
680 werner 637
                    .arg(world.x(),0,'f').arg(world.y(),0,'f')
599 werner 638
                    .arg(grid.cellsize()).arg(-9999);
694 werner 639
            QString line = gridToString(grid, QChar(' ')); // for normal grids (e.g. float)
640
            return result + line;
599 werner 641
}
642
 
15 Werner 643
#endif // GRID_H