Developer Documentation
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Modules Pages
adaptive_subdivider.cc
1 /* ========================================================================= *
2  * *
3  * OpenMesh *
4  * Copyright (c) 2001-2015, RWTH-Aachen University *
5  * Department of Computer Graphics and Multimedia *
6  * All rights reserved. *
7  * www.openmesh.org *
8  * *
9  *---------------------------------------------------------------------------*
10  * This file is part of OpenMesh. *
11  *---------------------------------------------------------------------------*
12  * *
13  * Redistribution and use in source and binary forms, with or without *
14  * modification, are permitted provided that the following conditions *
15  * are met: *
16  * *
17  * 1. Redistributions of source code must retain the above copyright notice, *
18  * this list of conditions and the following disclaimer. *
19  * *
20  * 2. Redistributions in binary form must reproduce the above copyright *
21  * notice, this list of conditions and the following disclaimer in the *
22  * documentation and/or other materials provided with the distribution. *
23  * *
24  * 3. Neither the name of the copyright holder nor the names of its *
25  * contributors may be used to endorse or promote products derived from *
26  * this software without specific prior written permission. *
27  * *
28  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS *
29  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED *
30  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A *
31  * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER *
32  * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, *
33  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, *
34  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR *
35  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF *
36  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING *
37  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS *
38  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *
39  * *
40  * ========================================================================= */
41 
42 /*===========================================================================*\
43  * *
44  * $Revision$ *
45  * $Date$ *
46  * *
47 \*===========================================================================*/
48 
49 // -------------------------------------------------------------- includes ----
50 
51 // -------------------- OpenMesh
52 #include <OpenMesh/Core/IO/MeshIO.hh>
53 #include <OpenMesh/Core/Mesh/TriMesh_ArrayKernelT.hh>
55 #include <OpenMesh/Tools/Utils/getopt.h>
56 // -------------------- OpenMesh Adaptive Composite Subdivider
59 // -------------------- STL
60 #include <iostream>
61 #include <fstream>
62 #include <sstream>
63 #include <limits>
64 #if defined(OM_CC_MIPS)
65 # include <math.h>
66 #else
67 # include <cmath>
68  using std::pow;
69 #endif
70 
71 
73 
74 // define mesh, rule interface, and subdivider types
78 
79 // ----------------------------------------------------------------------------
80 
81 using namespace OpenMesh::Subdivider;
82 
83 // factory function to add a RULE to a subdivider
84 #define ADD_FN( RULE ) \
85  bool add_ ## RULE( Subdivider& _sub ) \
86  { return _sub.add< Adaptive:: RULE < MyMesh > >(); }
87 
88 ADD_FN( Tvv3 );
89 ADD_FN( Tvv4 );
90 ADD_FN( VF );
91 ADD_FN( FF );
92 ADD_FN( FFc );
93 ADD_FN( FV );
94 ADD_FN( FVc );
95 ADD_FN( VV );
96 ADD_FN( VVc );
97 ADD_FN( VE );
98 ADD_FN( VdE );
99 ADD_FN( VdEc );
100 ADD_FN( EV );
101 ADD_FN( EVc );
102 ADD_FN( EF );
103 ADD_FN( FE );
104 ADD_FN( EdE );
105 ADD_FN( EdEc );
106 
107 #undef ADD_FN
108 
109 typedef bool (*add_rule_ft)( Subdivider& );
110 
111 // map rule name to factory function
112 struct RuleMap : std::map< std::string, add_rule_ft >
113 {
114  RuleMap()
115  {
116 #define ADD( RULE ) \
117  (*this)[ #RULE ] = add_##RULE;
118 
119  ADD( Tvv3 );
120  ADD( Tvv4 );
121  ADD( VF );
122  ADD( FF );
123  ADD( FFc );
124  ADD( FV );
125  ADD( FVc );
126  ADD( VV );
127  ADD( VVc );
128  ADD( VE );
129  ADD( VdE );
130  ADD( VdEc );
131  ADD( EV );
132  ADD( EVc );
133  ADD( EF );
134  ADD( FE );
135  ADD( EdE );
136  ADD( EdEc );
137 
138 #undef ADD
139  }
140 
141 } available_rules;
142 
143 
144 // ----------------------------------------------------------------------------
145 
146 std::string basename( const std::string& _fname );
147 void usage_and_exit(const std::string& _fname, int xcode);
148 
149 // ----------------------------------------------------------------------------
150 
151 
152 int main(int argc, char **argv)
153 {
154  size_t n_iter = 0; // n iteration
155  size_t max_nv = std::numeric_limits<size_t>::max(); // max. number of vertices in the end
156  std::string ifname; // input mesh
157  std::string ofname; // output mesh
158  std::string rule_sequence = "Tvv3 VF FF FVc"; // sqrt3 default
159  bool uniform = false;
160  int c;
161 
162  // ---------------------------------------- evaluate command line
163  while ( (c=getopt(argc, argv, "hlm:n:r:sU"))!=-1 )
164  {
165  switch(c)
166  {
167  case 's': rule_sequence = "Tvv3 VF FF FVc"; break; // sqrt3
168  case 'l': rule_sequence = "Tvv4 VdE EVc VdE EVc"; break; // loop
169  case 'n': { std::stringstream s; s << optarg; s >> n_iter; } break;
170  case 'm': { std::stringstream s; s << optarg; s >> max_nv; } break;
171  case 'r': rule_sequence = optarg; break;
172  case 'U': uniform = true; break;
173  case 'h': usage_and_exit(argv[0],0);
174  case '?':
175  default: usage_and_exit(argv[0],1);
176  }
177  }
178 
179  if ( optind == argc )
180  usage_and_exit(argv[0],2);
181 
182  if ( optind < argc )
183  ifname = argv[optind++];
184 
185  if ( optind < argc )
186  ofname = argv[optind++];
187 
188  // if ( optind < argc ) // too many arguments
189 
190  // ---------------------------------------- mesh and subdivider
191  MyMesh mesh;
192  Subdivider subdivider(mesh);
193 
194 
195  // -------------------- read mesh from file
196  std::cout << "Input mesh : " << ifname << std::endl;
197  if (!OpenMesh::IO::read_mesh(mesh, ifname))
198  {
199  std::cerr << " Error reading file!\n";
200  return 1;
201  }
202 
203  // store orignal size of mesh
204  size_t n_vertices = mesh.n_vertices();
205  size_t n_edges = mesh.n_edges();
206  size_t n_faces = mesh.n_faces();
207 
208  if ( n_iter > 0 )
209  std::cout << "Desired #iterations: " << n_iter << std::endl;
210 
211  if ( max_nv < std::numeric_limits<size_t>::max() )
212  {
213  std::cout << "Desired max. #V : " << max_nv << std::endl;
214  if (!n_iter )
215  n_iter = std::numeric_limits<size_t>::max();
216  }
217 
218 
219  // -------------------- Setup rule sequence
220  {
221  std::stringstream s;
222  std::string token;
223 
224  RuleMap::iterator it = available_rules.end();
225 
226  for (s << rule_sequence; s >> token; )
227  {
228  if ( (it=available_rules.find( token )) != available_rules.end() )
229  {
230  it->second( subdivider );
231  }
232  else if ( token[0]=='(' && (subdivider.n_rules() > 0) )
233  {
234  std::string::size_type beg(1);
235  if (token.length()==1)
236  {
237  s >> token;
238  beg = 0;
239  }
240 
241  std::string::size_type
242  end = token.find_last_of(')');
243  std::string::size_type
244  size = end==std::string::npos ? token.size()-beg : end-beg;
245 
246  std::stringstream v;
247  MyMesh::Scalar coeff;
248  std::cout << " " << token << std::endl;
249  std::cout << " " << beg << " " << end << " " << size << std::endl;
250  v << token.substr(beg, size);
251  v >> coeff;
252  std::cout << " coeffecient " << coeff << std::endl;
253  subdivider.rule( subdivider.n_rules()-1 ).set_coeff(coeff);
254 
255  if (end == std::string::npos)
256  {
257  s >> token;
258  if (token[0]!=')')
259  {
260  std::cerr << "Syntax error: Missing ')'\n";
261  return 1;
262  }
263  }
264  }
265  else
266  {
267  std::cerr << "Syntax error: " << token << "?\n";
268  return 1;
269  }
270  }
271  }
272 
273  std::cout << "Rule sequence : "
274  << subdivider.rules_as_string() << std::endl;
275 
276  // -------------------- Initialize subdivider
277  std::cout << "Initialize subdivider\n";
278  if (!subdivider.initialize())
279  {
280  std::cerr << " Error!\n";
281  return 1;
282  }
283 
284  //
285  MyMesh::FaceFaceIter ff_it;
286  double quality(0.0);
287 
288  // ---------------------------------------- subdivide
289  std::cout << "\nSubdividing...\n";
290 
291  OpenMesh::Utils::Timer timer, timer2;
292  size_t i;
293 
294  if ( uniform )
295  { // unifom
297  MyMesh::VertexIter v_it;
298  MyMesh::FaceHandle fh;
299  MyMesh::FaceIter f_it;
300 
301 
302  // raise all vertices to target state
303  timer.start();
304 
305  size_t n = n_iter;
306  size_t n_rules = subdivider.n_rules();
307 
308  i = 0;
309 
310  // calculate target states for faces and vertices
311  size_t target1 = (n - 1) * n_rules + subdivider.subdiv_rule().number() + 1;
312  size_t target2 = n * n_rules;
313 
314  for (f_it = mesh.faces_begin(); f_it != mesh.faces_end(); ++f_it) {
315 
316  if (mesh.data(*f_it).state() < int(target1) ) {
317  ++i;
318  fh = *f_it;
319  timer2.start();
320  subdivider.refine(fh);
321  timer2.stop();
322  }
323  }
324 
325  for (v_it = mesh.vertices_begin(); v_it != mesh.vertices_end(); ++v_it) {
326 
327  if (mesh.data(*v_it).state() < int(target2) ) {
328  vh = *v_it;
329  timer2.cont();
330  subdivider.refine(vh);
331  timer2.stop();
332  }
333  }
334  timer.stop();
335  }
336  else
337  { // adaptive
338 
339  MyMesh::FaceIter f_it;
340  MyMesh::FaceHandle fh;
341 
342  std::vector<double> __acos;
343  size_t buckets(3000);
344  double range(2.0);
345  double range2bucket(buckets/range);
346 
347  for (i = 0; i < buckets; ++i)
348  __acos.push_back( acos(-1.0 + i * range / buckets) );
349 
350  timer.start(); // total time needed
351 
352  // n iterations or until desired number of vertices reached approx.
353  for (i = 0; i < n_iter && mesh.n_vertices() < max_nv; ++i)
354  {
355  mesh.update_face_normals();
356 
357  // calculate quality
358  quality = 0.0;
359 
360  fh = *(mesh.faces_begin());
361 
362  // check every face
363  for (f_it = mesh.faces_begin(); f_it != mesh.faces_end(); ++f_it) {
364 
365  double face_quality = 0.0;
366  int valence = 0;
367 
368  for (ff_it = mesh.ff_iter(*f_it); ff_it.is_valid(); ++ff_it) {
369 
370  double temp_quality = OpenMesh::dot( mesh.normal(*f_it), mesh.normal(*ff_it) );
371 
372  if (temp_quality >= 1.0)
373  temp_quality = .99;
374  else if (temp_quality <= -1.0)
375  temp_quality = -.99;
376  temp_quality = (1.0+temp_quality) * range2bucket;
377  face_quality += __acos[int(temp_quality+.5)];
378 
379  ++valence;
380  }
381 
382  face_quality /= valence;
383 
384  // calaculate face area
385  MyMesh::Point p1, p2, p3;
386  MyMesh::Scalar area;
387 
388 #define heh halfedge_handle
389 #define nheh next_halfedge_handle
390 #define tvh to_vertex_handle
391 #define fvh from_vertex_handle
392  p1 = mesh.point(mesh.tvh(mesh.heh(*f_it)));
393  p2 = mesh.point(mesh.fvh(mesh.heh(*f_it)));
394  p3 = mesh.point(mesh.tvh(mesh.nheh(mesh.heh(*f_it))));
395 #undef heh
396 #undef nheh
397 #undef tvh
398 #undef fvh
399 
400  area = ((p2 - p1) % (p3 - p1)).norm();
401 
402  // weight face_quality
403  face_quality *= pow(double(area), double(.1));
404  //face_quality *= area;
405 
406  if (face_quality >= quality && !mesh.is_boundary(*f_it))
407  {
408  quality = face_quality;
409  fh = *f_it;
410  }
411  }
412 
413  // Subdivide Face
414  timer2.cont();
415  subdivider.refine(fh);
416  timer2.stop();
417  }
418 
419  // calculate time
420  timer.stop();
421 
422  } // uniform/adaptive?
423 
424  // calculate maximum refinement level
425  Adaptive::state_t max_level(0);
426 
427  for (MyMesh::VertexIter v_it = mesh.vertices_begin();
428  v_it != mesh.vertices_end(); ++v_it)
429  {
430  if (mesh.data(*v_it).state() > max_level)
431  max_level = mesh.data(*v_it).state();
432  }
433 
434 
435  // output results
436  std::cout << "\nDid " << i << (uniform ? " uniform " : "" )
437  << " subdivision steps in "
438  << timer.as_string()
439  << ", " << i/timer.seconds() << " steps/s\n";
440  std::cout << " only refinement: " << timer2.as_string()
441  << ", " << i/timer2.seconds() << " steps/s\n\n";
442 
443  std::cout << "Before: ";
444  std::cout << n_vertices << " Vertices, ";
445  std::cout << n_edges << " Edges, ";
446  std::cout << n_faces << " Faces. \n";
447 
448  std::cout << "Now : ";
449  std::cout << mesh.n_vertices() << " Vertices, ";
450  std::cout << mesh.n_edges() << " Edges, ";
451  std::cout << mesh.n_faces() << " Faces. \n\n";
452 
453  std::cout << "Maximum quality : " << quality << std::endl;
454  std::cout << "Maximum Subdivision Level: " << max_level/subdivider.n_rules()
455  << std::endl << std::endl;
456 
457  // ---------------------------------------- write mesh to file
458  {
459  if ( ofname.empty() )
460  {
461  std::stringstream s;
462 
463  s << "result." << subdivider.rules_as_string("_")
464  << "-" << i << "x.off";
465  s >> ofname;
466  }
467 
468  std::cout << "Output file: '" << ofname << "'.\n";
470  {
471  std::cerr << " Error writing file!\n";
472  return 1;
473  }
474  }
475  return 0;
476 }
477 
478 // ----------------------------------------------------------------------------
479 // helper
480 
481 void usage_and_exit(const std::string& _fname, int xcode)
482 {
483  using namespace std;
484 
485  cout << endl
486  << "Usage: " << basename(_fname)
487  << " [Options] input-mesh [output-mesh]\n\n";
488  cout << "\tAdaptively refine an input-mesh. The refined mesh is stored in\n"
489  << "\ta file named \"result.XXX.off\" (binary .off), if not specified\n"
490  << "\texplicitely (optional 2nd parameter of command line).\n\n";
491  cout << "Options:\n\n";
492  cout << "-m <int>\n\tAdaptively refine up to approx. <int> vertices.\n\n"
493  << "-n <int>\n\tAdaptively refine <int> times.\n\n"
494  << "-r <rule sequence>\n\tDefine a custom rule sequence.\n\n"
495  << "-l\n\tUse rule sequence for adaptive Loop.\n\n"
496  << "-s\n\tUse rule sequence for adaptive sqrt(3).\n\n"
497  << "-U\n\tRefine mesh uniformly (simulates uniform subdivision).\n\n";
498 
499  exit(xcode);
500 }
501 
502 std::string basename(const std::string& _f)
503 {
504  std::string::size_type dot = _f.rfind("/");
505  if (dot == std::string::npos)
506  return _f;
507  return _f.substr(dot+1, _f.length()-(dot+1));
508 }
509 
510 // ----------------------------------------------------------------------------
511 // end of file
512 // ============================================================================
std::string as_string(Format format=Automatic)
void start(void)
Start measurement.
double seconds(void) const
Returns measured time in seconds, if the timer is in state 'Stopped'.
osg::Vec3f::ValueType dot(const osg::Vec3f &_v1, const osg::Vec3f &_v2)
Adapter for osg vector member computing a scalar product.
Kernel::FaceFaceIter FaceFaceIter
Circulator.
Definition: PolyMeshT.hh:173
void update_face_normals()
Update normal vectors for all faces.
Definition: PolyMeshT.cc:262
bool write_mesh(const Mesh &_mesh, const std::string &_filename, Options _opt=Options::Default, std::streamsize _precision=6)
Write a mesh to the file _filename.
Definition: MeshIO.hh:199
Set binary mode for r/w.
Definition: Options.hh:105
CompositeTraits::state_t state_t
Kernel::Point Point
Coordinate type.
Definition: PolyMeshT.hh:115
bool read_mesh(Mesh &_mesh, const std::string &_filename)
Read a mesh from file _filename.
Definition: MeshIO.hh:104
STL namespace.
void stop(void)
Stop measurement.
void cont(void)
Continue measurement.
Kernel::VertexHandle VertexHandle
Handle for referencing the corresponding item.
Definition: PolyMeshT.hh:139
Kernel::Scalar Scalar
Scalar type.
Definition: PolyMeshT.hh:113