HeapT.hh 12 KB
Newer Older
Jan Möbius's avatar
Jan Möbius committed
1
/* ========================================================================= *
2
3
 *                                                                           *
 *                               OpenMesh                                    *
Jan Möbius's avatar
Jan Möbius committed
4
 *           Copyright (c) 2001-2015, RWTH-Aachen University                 *
Jan Möbius's avatar
Typo    
Jan Möbius committed
5
 *           Department of Computer Graphics and Multimedia                  *
Jan Möbius's avatar
Jan Möbius committed
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
 *                          All rights reserved.                             *
 *                            www.openmesh.org                               *
 *                                                                           *
 *---------------------------------------------------------------------------*
 * This file is part of OpenMesh.                                            *
 *---------------------------------------------------------------------------*
 *                                                                           *
 * Redistribution and use in source and binary forms, with or without        *
 * modification, are permitted provided that the following conditions        *
 * are met:                                                                  *
 *                                                                           *
 * 1. Redistributions of source code must retain the above copyright notice, *
 *    this list of conditions and the following disclaimer.                  *
 *                                                                           *
 * 2. Redistributions in binary form must reproduce the above copyright      *
 *    notice, this list of conditions and the following disclaimer in the    *
 *    documentation and/or other materials provided with the distribution.   *
 *                                                                           *
 * 3. Neither the name of the copyright holder nor the names of its          *
 *    contributors may be used to endorse or promote products derived from   *
 *    this software without specific prior written permission.               *
 *                                                                           *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS       *
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED *
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A           *
 * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER *
 * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,  *
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,       *
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR        *
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF    *
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING      *
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS        *
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.              *
Jan Möbius's avatar
Jan Möbius committed
39
40
 *                                                                           *
 * ========================================================================= */
41
42
43
44
45
46
47

/*===========================================================================*\
 *                                                                           *             
 *   $Revision$                                                         *
 *   $Date$                   *
 *                                                                           *
\*===========================================================================*/
Jan Möbius's avatar
Jan Möbius committed
48

Jan Möbius's avatar
Jan Möbius committed
49
/** \file Tools/Utils/HeapT.hh
Jan Möbius's avatar
Jan Möbius committed
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
    A generic heap class
**/
/** Martin, 26.12.2004: 
    1) replaced resize(size()-1) with pop_back(), since the later is more efficient
    2) replaced interface_.set_heap_position(entry(0), -1); with reset_heap_position()
    3) added const modifier to various functions
    TODO: in the moment the heap does not conform to the HeapInterface specification, 
          i.e., copies are passed instead of references. This is especially important 
          for set_heap_position(), where the reference argument is non-const. The 
          specification should be changed to reflect that the heap actually (only?)
          works when the heap entry is nothing more but a handle.
    TODO: change the specification of HeapInterface to make less(), greater() and
          get_heap_position() const. Needs changing DecimaterT. Might break 
          someone's code.
*/
    

//=============================================================================
//
//  CLASS HeapT
//
//=============================================================================

#ifndef OPENMESH_UTILS_HEAPT_HH
#define OPENMESH_UTILS_HEAPT_HH


//== INCLUDES =================================================================

#include "Config.hh"
#include <vector>
#include <OpenMesh/Core/System/omstream.hh>
82
#if _MSC_VER >= 1900 || __cplusplus > 199711L || defined(__GXX_EXPERIMENTAL_CXX0X__)
Hans-Christian Ebke's avatar
Hans-Christian Ebke committed
83
#include <utility>
84
#endif
Jan Möbius's avatar
Jan Möbius committed
85
86
87
88
89
90
91
92
93
94

//== NAMESPACE ================================================================

namespace OpenMesh { // BEGIN_NS_OPENMESH
namespace Utils { // BEGIN_NS_UTILS

//== CLASS DEFINITION =========================================================


/** This class demonstrates the HeapInterface's interface.  If you
Jan Möbius's avatar
Jan Möbius committed
95
 *  want to build your customized heap you will have to specify a heap
Jan Möbius's avatar
Jan Möbius committed
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
 *  interface class and use this class as a template parameter for the
 *  class HeapT. This class defines the interface that this heap
 *  interface has to implement.
 *   
 *  \see HeapT
 */
template <class HeapEntry>
struct HeapInterfaceT
{
  /// Comparison of two HeapEntry's: strict less
  bool less(const HeapEntry& _e1, const HeapEntry& _e2);

  /// Comparison of two HeapEntry's: strict greater
  bool greater(const HeapEntry& _e1, const HeapEntry& _e2);

  /// Get the heap position of HeapEntry _e
  int  get_heap_position(const HeapEntry& _e);

  /// Set the heap position of HeapEntry _e
  void set_heap_position(HeapEntry& _e, int _i);
};



/** \class HeapT HeapT.hh <OSG/Utils/HeapT.hh>
 *
 *  An efficient, highly customizable heap.
 *
Jan Möbius's avatar
Jan Möbius committed
124
125
 *  The main difference (and performance boost) of this heap compared
 *  to e.g. the heap of the STL is that here the positions of the
Jan Möbius's avatar
Jan Möbius committed
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
 *  heap's elements are accessible from the elements themself.
 *  Therefore if one changes the priority of an element one does not
 *  have to remove and re-insert this element, but can just call the
 *  update(HeapEntry) method.
 *
 *  This heap class is parameterized by two template arguments: 
 *  \li the class \c HeapEntry, that will be stored in the heap 
 *  \li the HeapInterface telling the heap how to compare heap entries and
 *      how to store the heap positions in the heap entries.
 *
 *  As an example how to use the class see declaration of class 
 *  Decimater::DecimaterT.
 *
 *  \see HeapInterfaceT
 */
 
template <class HeapEntry, class HeapInterface=HeapEntry>
class HeapT : private std::vector<HeapEntry>
{
private: 
  typedef std::vector<HeapEntry>            Base;
  
public:

  /// Constructor
  HeapT() : HeapVector() {}
  
153
#if _MSC_VER >= 1900 || __cplusplus > 199711L || defined(__GXX_EXPERIMENTAL_CXX0X__)
Jan Möbius's avatar
Jan Möbius committed
154
  /// Construct with a given \c HeapIterface. 
Hans-Christian Ebke's avatar
Hans-Christian Ebke committed
155
156
  HeapT(HeapInterface _interface)
  : HeapVector(),  interface_(std::move(_interface))
Jan Möbius's avatar
Jan Möbius committed
157
  {}
158
159
160
161
162
163
164
#else
  /// Construct with a given \c HeapIterface.
  HeapT(const HeapInterface &_interface)
  : HeapVector(),  interface_(_interface)
  {}
#endif

Jan Möbius's avatar
Jan Möbius committed
165
166
167
  /// Destructor.
  ~HeapT(){};

Hans-Christian Ebke's avatar
Hans-Christian Ebke committed
168
169
170
171
172
173
174
  HeapInterface &getInterface() {
      return interface_;
  }

  const HeapInterface &getInterface() const {
      return interface_;
  }
Jan Möbius's avatar
Jan Möbius committed
175
176
177
178
179
180
181
182

  /// clear the heap
  void clear() { HeapVector::clear(); }

  /// is heap empty?
  bool empty() const { return HeapVector::empty(); }

  /// returns the size of heap
183
  size_t size() const { return HeapVector::size(); }
Jan Möbius's avatar
Jan Möbius committed
184
185

  /// reserve space for _n entries
186
  void reserve(size_t _n) { HeapVector::reserve(_n); }
Jan Möbius's avatar
Jan Möbius committed
187
188
189
190
191
192
193
194
195
196
197
198

  /// reset heap position to -1 (not in heap)
  void reset_heap_position(HeapEntry _h)
  { interface_.set_heap_position(_h, -1); }
  
  /// is an entry in the heap?
  bool is_stored(HeapEntry _h)
  { return interface_.get_heap_position(_h) != -1; }
  
  /// insert the entry _h
  void insert(HeapEntry _h)  
  { 
199
    this->push_back(_h); 
Jan Möbius's avatar
Jan Möbius committed
200
201
202
203
204
205
206
    upheap(size()-1); 
  }

  /// get the first entry
  HeapEntry front() const
  { 
    assert(!empty()); 
Hans-Christian Ebke's avatar
Hans-Christian Ebke committed
207
    return HeapVector::front();
Jan Möbius's avatar
Jan Möbius committed
208
209
210
211
212
213
  }

  /// delete the first entry
  void pop_front()
  {    
    assert(!empty());
Hans-Christian Ebke's avatar
Hans-Christian Ebke committed
214
    reset_heap_position(HeapVector::front());
Jan Möbius's avatar
Jan Möbius committed
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
    if (size() > 1)
    {
      entry(0, entry(size()-1));
      Base::pop_back();
      downheap(0);
    }
    else
    {
      Base::pop_back();
    }
  }

  /// remove an entry
  void remove(HeapEntry _h)
  {
    int pos = interface_.get_heap_position(_h);
    reset_heap_position(_h);

    assert(pos != -1);
    assert((unsigned int) pos < size());
    
    // last item ?
    if ((unsigned int) pos == size()-1)
    {
      Base::pop_back();    
    }
    else 
    {
      entry(pos, entry(size()-1)); // move last elem to pos
      Base::pop_back();
      downheap(pos);
      upheap(pos);
    }
  }

  /** update an entry: change the key and update the position to
      reestablish the heap property.
  */
  void update(HeapEntry _h)
  {
    int pos = interface_.get_heap_position(_h);
    assert(pos != -1);
    assert((unsigned int)pos < size());
    downheap(pos);
    upheap(pos);
  }
  
  /// check heap condition
  bool check()
  {
    bool ok(true);
    unsigned int i, j;
    for (i=0; i<size(); ++i)
    {
      if (((j=left(i))<size()) && interface_.greater(entry(i), entry(j))) 
      {
Jan Möbius's avatar
Jan Möbius committed
271
272
        omerr() << "Heap condition violated\n";
        ok=false;
Jan Möbius's avatar
Jan Möbius committed
273
274
275
      }
      if (((j=right(i))<size()) && interface_.greater(entry(i), entry(j)))
      {
Jan Möbius's avatar
Jan Möbius committed
276
277
        omerr() << "Heap condition violated\n";
        ok=false;
Jan Möbius's avatar
Jan Möbius committed
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
      }
    }
    return ok;
  }

protected:  
  /// Instance of HeapInterface
  HeapInterface interface_;

private:
  // typedef
  typedef std::vector<HeapEntry> HeapVector;

  
  /// Upheap. Establish heap property.
Jan Möbius's avatar
Jan Möbius committed
293
  void upheap(size_t _idx);
Jan Möbius's avatar
Jan Möbius committed
294
295
296

  
  /// Downheap. Establish heap property.
Jan Möbius's avatar
Jan Möbius committed
297
  void downheap(size_t _idx);
Jan Möbius's avatar
Jan Möbius committed
298
299
300

  
  /// Get the entry at index _idx
Jan Möbius's avatar
Jan Möbius committed
301
  inline HeapEntry entry(size_t _idx) const
Jan Möbius's avatar
Jan Möbius committed
302
303
304
305
306
307
308
  {
    assert(_idx < size());
    return (Base::operator[](_idx));
  }

  
  /// Set entry _h to index _idx and update _h's heap position.
Jan Möbius's avatar
Jan Möbius committed
309
  inline void entry(size_t _idx, HeapEntry _h)
Jan Möbius's avatar
Jan Möbius committed
310
311
312
  {
    assert(_idx < size());
    Base::operator[](_idx) = _h;
Jan Möbius's avatar
Jan Möbius committed
313
    interface_.set_heap_position(_h, int(_idx));
Jan Möbius's avatar
Jan Möbius committed
314
315
316
317
  }

  
  /// Get parent's index
Jan Möbius's avatar
Jan Möbius committed
318
  inline size_t parent(size_t _i) { return (_i-1)>>1; }
Jan Möbius's avatar
Jan Möbius committed
319
  /// Get left child's index
Jan Möbius's avatar
Jan Möbius committed
320
  inline size_t left(size_t _i)   { return (_i<<1)+1; }
Jan Möbius's avatar
Jan Möbius committed
321
  /// Get right child's index
Jan Möbius's avatar
Jan Möbius committed
322
  inline size_t right(size_t _i)  { return (_i<<1)+2; }
Jan Möbius's avatar
Jan Möbius committed
323
324
325
326
327
328
329
330
331
332
333
334

};




//== IMPLEMENTATION ========================================================== 


template <class HeapEntry, class HeapInterface>
void
HeapT<HeapEntry, HeapInterface>::
Jan Möbius's avatar
Jan Möbius committed
335
upheap(size_t _idx)
Jan Möbius's avatar
Jan Möbius committed
336
337
{
  HeapEntry     h = entry(_idx);
Jan Möbius's avatar
Jan Möbius committed
338
  size_t        parentIdx;
Jan Möbius's avatar
Jan Möbius committed
339

Jan Möbius's avatar
Jan Möbius committed
340
  while ((_idx>0) && interface_.less(h, entry(parentIdx=parent(_idx))))
Jan Möbius's avatar
Jan Möbius committed
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
  {
    entry(_idx, entry(parentIdx));
    _idx = parentIdx;    
  }
  
  entry(_idx, h);
}
  

//-----------------------------------------------------------------------------

  
template <class HeapEntry, class HeapInterface>
void
HeapT<HeapEntry, HeapInterface>::
Jan Möbius's avatar
Jan Möbius committed
356
downheap(size_t _idx)
Jan Möbius's avatar
Jan Möbius committed
357
{
Hans-Christian Ebke's avatar
Hans-Christian Ebke committed
358
  const HeapEntry     h = entry(_idx);
Jan Möbius's avatar
Jan Möbius committed
359
  size_t        childIdx;
Hans-Christian Ebke's avatar
Hans-Christian Ebke committed
360
  const size_t        s = size();
Jan Möbius's avatar
Jan Möbius committed
361
362
363
364
365
366
  
  while(_idx < s)
  {
    childIdx = left(_idx);
    if (childIdx >= s) break;
    
Jan Möbius's avatar
Jan Möbius committed
367
    if ((childIdx + 1 < s) && (interface_.less(entry(childIdx + 1), entry(childIdx))))
Jan Möbius's avatar
Jan Möbius committed
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
      ++childIdx;
    
    if (interface_.less(h, entry(childIdx))) break;

    entry(_idx, entry(childIdx));
    _idx = childIdx;
  }  

  entry(_idx, h);
}


//=============================================================================
} // END_NS_UTILS
} // END_NS_OPENMESH
//=============================================================================
#endif // OSG_HEAP_HH defined
//=============================================================================