McDecimaterT_impl.hh 16.1 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
 *                          All rights reserved.                             *
 *                            www.openmesh.org                               *
8
 *                                                                           *
9
 *---------------------------------------------------------------------------*
Jan Möbius's avatar
Jan Möbius committed
10 11
 * This file is part of OpenMesh.                                            *
 *---------------------------------------------------------------------------*
12
 *                                                                           *
Jan Möbius's avatar
Jan Möbius committed
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
 * 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
/** \file McDecimaterT_impl.hh
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
 */

//=============================================================================
//
//  CLASS McDecimaterT - IMPLEMENTATION
//
//=============================================================================
#define OPENMESH_MULTIPLE_CHOICE_DECIMATER_DECIMATERT_CC

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

#include <OpenMesh/Tools/Decimater/McDecimaterT.hh>

#include <vector>
#if defined(OM_CC_MIPS)
#  include <float.h>
#else
#  include <cfloat>
#endif
Jan Möbius's avatar
Jan Möbius committed
63

64 65 66
#ifdef WIN32
# include <OpenMesh/Core/Utils/RandomNumberGenerator.hh>
#endif
67 68 69 70 71 72 73 74 75 76

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

namespace OpenMesh {
namespace Decimater {

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

template<class Mesh>
McDecimaterT<Mesh>::McDecimaterT(Mesh& _mesh) :
77 78
  BaseDecimaterT<Mesh>(_mesh),
    mesh_(_mesh), randomSamples_(10) {
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103

  // default properties
  mesh_.request_vertex_status();
  mesh_.request_halfedge_status();
  mesh_.request_edge_status();
  mesh_.request_face_status();

}

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

template<class Mesh>
McDecimaterT<Mesh>::~McDecimaterT() {
  // default properties
  mesh_.release_vertex_status();
  mesh_.release_edge_status();
  mesh_.release_halfedge_status();
  mesh_.release_face_status();

}

//-----------------------------------------------------------------------------
template<class Mesh>
size_t McDecimaterT<Mesh>::decimate(size_t _n_collapses) {

104
  if (!this->is_initialized())
105 106 107 108
    return 0;

  unsigned int n_collapses(0);

109 110 111 112 113 114 115
  bool collapsesUnchanged = false;
  // old n_collapses in order to check for convergence
  unsigned int oldCollapses = 0;
  // number of iterations where no new collapses where
  // performed in a row
  unsigned int noCollapses = 0;

116 117 118 119
#ifdef WIN32
  RandomNumberGenerator randGen(mesh_.n_halfedges());
#endif

120 121
  const bool update_normals = mesh_.has_face_normals();

122
  while ( n_collapses <  _n_collapses) {
Jan Möbius's avatar
Jan Möbius committed
123

124 125 126 127
    if (noCollapses > 20) {
      omlog() << "[McDecimater] : no collapses performed in over 20 iterations in a row\n";
      break;
    }
128 129 130

    // Optimal id and value will be collected during the random sampling
    typename Mesh::HalfedgeHandle bestHandle(-1);
131
    typename Mesh::HalfedgeHandle tmpHandle(-1);
132
    double bestEnergy = FLT_MAX;
133
    double energy = FLT_MAX;
134 135

    // Generate random samples for collapses
Isaak Lim's avatar
Isaak Lim committed
136
    for ( int i = 0; i < (int)randomSamples_; ++i) {
137 138

      // Random halfedge handle
139
#ifdef WIN32
Isaak Lim's avatar
Isaak Lim committed
140
      tmpHandle = typename Mesh::HalfedgeHandle(int(randGen.getRand() * double(mesh_.n_halfedges() - 1.0)) );
141
#else
142
      tmpHandle = typename Mesh::HalfedgeHandle( (double(rand()) / double(RAND_MAX) ) * double(mesh_.n_halfedges()-1) );
143
#endif
144 145 146 147 148 149 150

      // if it is not deleted, we analyse it
      if ( ! mesh_.status(tmpHandle).deleted()  ) {

        CollapseInfo ci(mesh_, tmpHandle);

        // Check if legal we analyze the priority of this collapse operation
151
        if (this->is_collapse_legal(ci)) {
Jan Möbius's avatar
Jan Möbius committed
152 153 154 155 156 157 158 159
            energy = this->collapse_priority(ci);

            if (energy != ModBaseT<Mesh>::ILLEGAL_COLLAPSE) {
              // Check if the current samples energy is better than any energy before
              if ( energy < bestEnergy ) {
                bestEnergy = energy;
                bestHandle = tmpHandle;
              }
160
            }
161 162 163 164 165 166 167 168 169 170 171 172 173 174
        } else {
          continue;
        }
      }

    }

    // Found the best energy?
    if ( bestEnergy != FLT_MAX ) {

      // setup collapse info
      CollapseInfo ci(mesh_, bestHandle);

      // check topological correctness AGAIN !
175
      if (!this->is_collapse_legal(ci))
176 177 178
        continue;

      // pre-processing
179
      this->preprocess_collapse(ci);
180 181 182 183 184

      // perform collapse
      mesh_.collapse(bestHandle);
      ++n_collapses;

185 186 187 188 189
      // store current collapses state
      oldCollapses = n_collapses;
      noCollapses = 0;
      collapsesUnchanged = false;

190
      // update triangle normals
191 192 193 194 195 196 197
      if (update_normals)
      {
        typename Mesh::VertexFaceIter vf_it = mesh_.vf_iter(ci.v1);
        for (; vf_it.is_valid(); ++vf_it)
          if (!mesh_.status(*vf_it).deleted())
            mesh_.set_normal(*vf_it, mesh_.calc_face_normal(*vf_it));
      }
198 199

      // post-process collapse
200
      this->postprocess_collapse(ci);
201

202 203 204 205
      // notify observer and stop if the observer requests it
      if (!this->notify_observer(n_collapses))
          return n_collapses;

206 207 208 209 210 211 212 213 214
    } else {
      if (oldCollapses == n_collapses) {
        if (collapsesUnchanged == false) {
          noCollapses = 1;
          collapsesUnchanged = true;
        } else {
          noCollapses++;
        }
      }
215 216 217 218 219 220 221 222 223 224 225 226
    }

  }

  // DON'T do garbage collection here! It's up to the application.
  return n_collapses;
}

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

template<class Mesh>
size_t McDecimaterT<Mesh>::decimate_to_faces(size_t _nv, size_t _nf) {
Jan Möbius's avatar
Jan Möbius committed
227

228
  if (!this->is_initialized())
229 230
    return 0;

231 232 233 234
  // check if no vertex or face contraints were set
  if ( (_nv == 0) && (_nf == 1) )
    return decimate_constraints_only(1.0);

235 236
  size_t nv = mesh_.n_vertices();
  size_t nf = mesh_.n_faces();
237 238
  unsigned int n_collapses(0);

239

240 241 242 243 244 245
  bool collapsesUnchanged = false;
  // old n_collapses in order to check for convergence
  unsigned int oldCollapses = 0;
  // number of iterations where no new collapses where
  // performed in a row
  unsigned int noCollapses = 0;
246

247 248 249 250
#ifdef WIN32
  RandomNumberGenerator randGen(mesh_.n_halfedges());
#endif

251 252
  const bool update_normals = mesh_.has_face_normals();

Jan Möbius's avatar
Jan Möbius committed
253
  while ((_nv < nv) && (_nf < nf)) {
Jan Möbius's avatar
Jan Möbius committed
254

255 256 257 258
    if (noCollapses > 20) {
      omlog() << "[McDecimater] : no collapses performed in over 20 iterations in a row\n";
      break;
    }
259 260 261

    // Optimal id and value will be collected during the random sampling
    typename Mesh::HalfedgeHandle bestHandle(-1);
262
    typename Mesh::HalfedgeHandle tmpHandle(-1);
263
    double bestEnergy = FLT_MAX;
264 265
    double energy = FLT_MAX;

266
    // Generate random samples for collapses
Jan Möbius's avatar
Jan Möbius committed
267
    for (int i = 0; i < (int) randomSamples_; ++i) {
268 269

      // Random halfedge handle
270
#ifdef WIN32
Isaak Lim's avatar
Isaak Lim committed
271
      tmpHandle = typename Mesh::HalfedgeHandle(int(randGen.getRand() * double(mesh_.n_halfedges() - 1.0)) );
272
#else
273
      tmpHandle = typename Mesh::HalfedgeHandle( ( double(rand()) / double(RAND_MAX) ) * double(mesh_.n_halfedges() - 1));
274
#endif
275 276

      // if it is not deleted, we analyse it
Jan Möbius's avatar
Jan Möbius committed
277
      if (!mesh_.status(tmpHandle).deleted()) {
278 279 280 281

        CollapseInfo ci(mesh_, tmpHandle);

        // Check if legal we analyze the priority of this collapse operation
Matthias Möller's avatar
Matthias Möller committed
282
        if (this->is_collapse_legal(ci)) {
Jan Möbius's avatar
Jan Möbius committed
283 284 285 286 287 288 289 290
            energy = this->collapse_priority(ci);

            if (energy != ModBaseT<Mesh>::ILLEGAL_COLLAPSE) {
              // Check if the current samples energy is better than any energy before
              if (energy < bestEnergy) {
                bestEnergy = energy;
                bestHandle = tmpHandle;
              }
291
            }
292 293 294 295 296 297 298
        } else {
          continue;
        }
      }

    }

299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332
    // Found the best energy?
    if ( bestEnergy != FLT_MAX ) {

      // setup collapse info
      CollapseInfo ci(mesh_, bestHandle);

      // check topological correctness AGAIN !
      if (!this->is_collapse_legal(ci))
        continue;

      // adjust complexity in advance (need boundary status)

      // One vertex is killed by the collapse
      --nv;

      // If we are at a boundary, one face is lost,
      // otherwise two
      if (mesh_.is_boundary(ci.v0v1) || mesh_.is_boundary(ci.v1v0))
        --nf;
      else
        nf -= 2;

      // pre-processing
      this->preprocess_collapse(ci);

      // perform collapse
      mesh_.collapse(bestHandle);
      ++n_collapses;

      // store current collapses state
      oldCollapses = n_collapses;
      noCollapses = 0;
      collapsesUnchanged = false;

333 334 335 336 337 338 339 340
      if (update_normals)
      {
        // update triangle normals
        typename Mesh::VertexFaceIter vf_it = mesh_.vf_iter(ci.v1);
        for (; vf_it.is_valid(); ++vf_it)
          if (!mesh_.status(*vf_it).deleted())
            mesh_.set_normal(*vf_it, mesh_.calc_face_normal(*vf_it));
      }
341 342 343 344

      // post-process collapse
      this->postprocess_collapse(ci);

345 346 347 348
      // notify observer and stop if the observer requests it
      if (!this->notify_observer(n_collapses))
          return n_collapses;

349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369
    } else {
      if (oldCollapses == n_collapses) {
        if (collapsesUnchanged == false) {
          noCollapses = 1;
          collapsesUnchanged = true;
        } else {
          noCollapses++;
        }
      }
    }

  }

  // DON'T do garbage collection here! It's up to the application.
  return n_collapses;
}

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

template<class Mesh>
size_t McDecimaterT<Mesh>::decimate_constraints_only(float _factor) {
Jan Möbius's avatar
Jan Möbius committed
370

371 372 373 374 375 376 377
  if (!this->is_initialized())
    return 0;

  if (_factor < 1.0)
    this->set_error_tolerance_factor(_factor);

  unsigned int n_collapses(0);
Jan Möbius's avatar
Jan Möbius committed
378 379
  size_t       nv = mesh_.n_vertices();
  size_t       nf = mesh_.n_faces();
380 381

  bool lastCollapseIllegal = false;
Jan Möbius's avatar
Jan Möbius committed
382
  // number of illegal collapses that occurred in a row
383 384 385 386 387 388 389 390 391
  unsigned int illegalCollapses = 0;

  bool collapsesUnchanged = false;
  // old n_collapses in order to check for convergence
  unsigned int oldCollapses = 0;
  // number of iterations where no new collapses where
  // performed in a row
  unsigned int noCollapses = 0;

Jan Möbius's avatar
Jan Möbius committed
392 393
  double energy     = FLT_MAX;
  double bestEnergy = FLT_MAX;
394

395 396 397 398
#ifdef WIN32
  RandomNumberGenerator randGen(mesh_.n_halfedges());
#endif

Jan Möbius's avatar
Jan Möbius committed
399
  while ((noCollapses <= 50) && (illegalCollapses <= 50) && (nv > 0) && (nf > 1)) {
400 401 402 403

    // Optimal id and value will be collected during the random sampling
    typename Mesh::HalfedgeHandle bestHandle(-1);
    typename Mesh::HalfedgeHandle tmpHandle(-1);
Jan Möbius's avatar
Jan Möbius committed
404 405
    bestEnergy = FLT_MAX;

406 407

#ifndef WIN32
Jan Möbius's avatar
Jan Möbius committed
408
    const double randomNormalizer = (1.0 / RAND_MAX) * (mesh_.n_halfedges() - 1);
409
#endif
410 411

    // Generate random samples for collapses
Jan Möbius's avatar
Jan Möbius committed
412
    for (int i = 0; i < (int) randomSamples_; ++i) {
413 414

      // Random halfedge handle
415
#ifdef WIN32
Isaak Lim's avatar
Isaak Lim committed
416
      tmpHandle = typename Mesh::HalfedgeHandle(int(randGen.getRand()  * double(mesh_.n_halfedges() - 1.0)) );
417
#else
Jan Möbius's avatar
Jan Möbius committed
418
      tmpHandle = typename Mesh::HalfedgeHandle(int(rand() * randomNormalizer ) );
419
#endif
420

Jan Möbius's avatar
Jan Möbius committed
421 422
      // if it is not deleted, we analyze it
      if (!mesh_.status(mesh_.edge_handle(tmpHandle)).deleted()) {
423 424 425 426 427 428

        CollapseInfo ci(mesh_, tmpHandle);

        // Check if legal we analyze the priority of this collapse operation
        if (this->is_collapse_legal(ci)) {

Jan Möbius's avatar
Jan Möbius committed
429
            energy = this->collapse_priority(ci);
430

Jan Möbius's avatar
Jan Möbius committed
431 432 433 434 435 436 437
            if (energy == ModBaseT<Mesh>::ILLEGAL_COLLAPSE) {
              if (lastCollapseIllegal) {
                illegalCollapses++;
              } else {
                illegalCollapses = 1;
                lastCollapseIllegal = true;
              }
438
            } else {
Jan Möbius's avatar
Jan Möbius committed
439

Jan Möbius's avatar
Jan Möbius committed
440 441 442 443 444 445 446 447
              illegalCollapses = 0;
              lastCollapseIllegal = false;

              // Check if the current samples energy is better than any energy before
              if (energy < bestEnergy) {
                bestEnergy = energy;
                bestHandle = tmpHandle;
              }
448 449
            }
        } else {
Jan Möbius's avatar
Jan Möbius committed
450

451 452 453
          continue;
        }
      }
454 455 456

    }

Jan Möbius's avatar
Jan Möbius committed
457 458


459 460 461 462 463 464 465
    // Found the best energy?
    if ( bestEnergy != FLT_MAX ) {

      // setup collapse info
      CollapseInfo ci(mesh_, bestHandle);

      // check topological correctness AGAIN !
Matthias Möller's avatar
Matthias Möller committed
466
      if (!this->is_collapse_legal(ci))
467 468 469 470 471 472 473 474 475 476 477 478 479 480 481
        continue;

      // adjust complexity in advance (need boundary status)

      // One vertex is killed by the collapse
      --nv;

      // If we are at a boundary, one face is lost,
      // otherwise two
      if (mesh_.is_boundary(ci.v0v1) || mesh_.is_boundary(ci.v1v0))
        --nf;
      else
        nf -= 2;

      // pre-processing
Matthias Möller's avatar
Matthias Möller committed
482
      this->preprocess_collapse(ci);
483 484 485 486 487

      // perform collapse
      mesh_.collapse(bestHandle);
      ++n_collapses;

488 489 490 491 492 493
      // store current collapses state
      oldCollapses = n_collapses;
      noCollapses = 0;
      collapsesUnchanged = false;


494 495
      // update triangle normals
      typename Mesh::VertexFaceIter vf_it = mesh_.vf_iter(ci.v1);
496 497 498
      for (; vf_it.is_valid(); ++vf_it)
        if (!mesh_.status(*vf_it).deleted())
          mesh_.set_normal(*vf_it, mesh_.calc_face_normal(*vf_it));
499 500

      // post-process collapse
Matthias Möller's avatar
Matthias Möller committed
501
      this->postprocess_collapse(ci);
502

503 504 505 506
      // notify observer and stop if the observer requests it
      if (!this->notify_observer(n_collapses))
          return n_collapses;

507 508 509 510 511 512 513 514 515
    } else {
      if (oldCollapses == n_collapses) {
        if (collapsesUnchanged == false) {
          noCollapses = 1;
          collapsesUnchanged = true;
        } else {
          noCollapses++;
        }
      }
516 517 518 519
    }

  }

520 521 522
  if (_factor < 1.0)
    this->set_error_tolerance_factor(1.0);

523 524
  // DON'T do garbage collection here! It's up to the application.
  return n_collapses;
525

526 527 528 529 530 531 532
}

//=============================================================================
}// END_NS_MC_DECIMATER
} // END_NS_OPENMESH
//=============================================================================