Beispiel #1
0
int main (int argc, char** argv)
{
  UnitTest t (32);

  // Path ();
  Path p0;
  t.is (p0._data, "", "Path::Path");

  // Path (const Path&);
  Path p1 = Path ("foo");
  t.is (p1._data, Directory::cwd () + "/foo", "Path::operator=");

  // Path (const std::string&);
  Path p2 ("~");
  t.ok (p2._data != "~", "~ expanded to " + p2._data);

  Path p3 ("/tmp");
  t.ok (p3._data == "/tmp", "/tmp -> /tmp");

  // Path& operator= (const Path&);
  Path p3_copy (p3);
  t.is (p3._data, p3_copy._data, "Path::Path (Path&)");

  // operator (std::string) const;
  t.is ((std::string) p3, "/tmp", "Path::operator (std::string) const");

  // std::string name () const;
  Path p4 ("/a/b/c/file.ext");
  t.is (p4.name (), "file.ext",  "/a/b/c/file.ext name is file.ext");

  // std::string parent () const;
  t.is (p4.parent (), "/a/b/c",  "/a/b/c/file.ext parent is /a/b/c");

  // std::string extension () const;
  t.is (p4.extension (), "ext",  "/a/b/c/file.ext extension is ext");

  // bool exists () const;
  t.ok (p2.exists (), "~ exists");
  t.ok (p3.exists (), "/tmp exists");

  // bool is_directory () const;
  t.ok (p2.is_directory (), "~ is_directory");
  t.ok (p3.is_directory (), "/tmp is_directory");

  // bool readable () const;
  t.ok (p2.readable (), "~ readable");
  t.ok (p3.readable (), "/tmp readable");

  // bool writable () const;
  t.ok (p2.writable (), "~ writable");
  t.ok (p3.writable (), "/tmp writable");

  // bool executable () const;
  t.ok (p2.executable (), "~ executable");
  t.ok (p3.executable (), "/tmp executable");

  // static std::string expand (const std::string&);
  t.ok (Path::expand ("~") != "~", "Path::expand ~ != ~");
  t.ok (Path::expand ("~/") != "~/", "Path::expand ~/ != ~/");

  // static std::vector <std::string> glob (const std::string&);
  std::vector <std::string> out = Path::glob ("/tmp");
  t.ok (out.size () == 1, "/tmp -> 1 result");
  t.is (out[0], "/tmp", "/tmp -> /tmp");

  out = Path::glob ("/t?p");
  t.ok (out.size () == 1, "/t?p -> 1 result");
  t.is (out[0], "/tmp", "/t?p -> /tmp");

  out = Path::glob ("/[s-u]mp");
  t.ok (out.size () == 1, "/[s-u]mp -> 1 result");
  t.is (out[0], "/tmp", "/[s-u]mp -> /tmp");

  // bool is_absolute () const;
  t.notok (p0.is_absolute (), "'' !is_absolute");
  t.ok    (p1.is_absolute (), "foo is_absolute");
  t.ok    (p2.is_absolute (), "~ is_absolute (after expansion)");
  t.ok    (p3.is_absolute (), "/tmp is_absolute");
  t.ok    (p4.is_absolute (), "/a/b/c/file.ext is_absolute");

  return 0;
}
Beispiel #2
0
int
run_main (int, ACE_TCHAR *[])
{
  ACE_START_TEST (ACE_TEXT ("Bound_Ptr_Test"));


  // =========================================================================
  // The following test uses the ACE_Strong_Bound_Ptr in a single
  // thread of control, hence we use the ACE_Null_Mutex

  ACE_DEBUG ((LM_DEBUG,
              ACE_TEXT ("(%t) performing synchronous test...\n")));

  Parent *parent1 = 0;
  ACE_NEW_RETURN (parent1,
                  Parent,
                  -1);
  ACE_Weak_Bound_Ptr<Parent, ACE_Null_Mutex> p8;
  {
    // Must get the pointer from the parent object's weak_self_ member.
    ACE_Strong_Bound_Ptr<Parent, ACE_Null_Mutex> p(parent1->weak_self_);
    ACE_Strong_Bound_Ptr<Parent, ACE_Null_Mutex> p1(p);
    ACE_Strong_Bound_Ptr<Parent, ACE_Null_Mutex> p2(p);
    ACE_Weak_Bound_Ptr<Parent, ACE_Null_Mutex> p3(p);
    ACE_Strong_Bound_Ptr<Parent, ACE_Null_Mutex> p4(p);
    ACE_Strong_Bound_Ptr<Parent, ACE_Null_Mutex> p5 = p2;
    ACE_Strong_Bound_Ptr<Parent, ACE_Null_Mutex> p6 = p3;
    ACE_Weak_Bound_Ptr<Parent, ACE_Null_Mutex> p7(p1);
    p8 = p2;
    p->child_->do_something ();
  }
  ACE_DEBUG ((LM_DEBUG,
              ACE_TEXT ("(%t) Parent instance count is %d, expecting 0\n"),
              Parent::instance_count_));
  if (Parent::instance_count_ != 0)
    {
      ACE_ERROR_RETURN ((LM_ERROR,
                         ACE_TEXT ("(%t) parent instance count not 0...\n")),
                         -1);
    }
  ACE_DEBUG ((LM_DEBUG,
              ACE_TEXT ("(%t) Child instance count is %d, expecting 0\n"),
              Child::instance_count_));
  if (Child::instance_count_ != 0)
    {
      ACE_ERROR_RETURN ((LM_ERROR,
                         ACE_TEXT ("(%t) child instance count not 0...\n")),
                         -1);
    }
  // Weak pointer should now be set to null.
  if(!p8.null ())
    {
      ACE_ERROR_RETURN ((LM_ERROR,
                         ACE_TEXT ("(%t) p8 not nill...\n")),
                         -1);
    }

  Printer *printer1 = 0;
  ACE_NEW_RETURN (printer1,
                  Printer ("I am printer 1"),
                  -1);
  ACE_Weak_Bound_Ptr<Printer, ACE_Null_Mutex> r9;
  {
    ACE_Strong_Bound_Ptr<Printer, ACE_Null_Mutex> r(printer1);
    ACE_Strong_Bound_Ptr<Printer, ACE_Null_Mutex> r1(r);
    ACE_Strong_Bound_Ptr<Printer, ACE_Null_Mutex> r2(r);
    ACE_Strong_Bound_Ptr<Printer, ACE_Null_Mutex> r3(r);
    ACE_Strong_Bound_Ptr<Printer, ACE_Null_Mutex> r4(r);
    ACE_Strong_Bound_Ptr<Printer, ACE_Null_Mutex> r5 = r2;
    ACE_Strong_Bound_Ptr<Printer, ACE_Null_Mutex> r6 = r1;
    ACE_Weak_Bound_Ptr<Printer, ACE_Null_Mutex> r7(r1);
    ACE_Weak_Bound_Ptr<Printer, ACE_Null_Mutex> r8 = r2;
    r9 = r3;
    r9->print ();
  }
  ACE_DEBUG ((LM_DEBUG,
              ACE_TEXT ("(%t) Printer instance count is %d, expecting 0\n"),
              Printer::instance_count_));
  if (Printer::instance_count_ != 0)
    {
      ACE_ERROR_RETURN ((LM_ERROR,
                         ACE_TEXT ("(%t) Printer instance count not 0...\n")),
                         -1);
    }
  // Weak pointer should now be set to null.
  if (!r9.null ())
    {
      ACE_ERROR_RETURN ((LM_ERROR,
                         ACE_TEXT ("(%t) r9 not nill...\n")),
                         -1);
    }

#if defined (ACE_HAS_THREADS)

  // =========================================================================
  // The following test uses the ACE_Strong_Bound_Ptr in multiple
  // threads of control.

  ACE_DEBUG ((LM_DEBUG,
              ACE_TEXT ("(%t) performing asynchronous test...\n")));

  Scheduler *scheduler_ptr = 0;

  // Create active objects..
  ACE_NEW_RETURN (scheduler_ptr,
                  Scheduler (),
                  -1);

  ACE_Strong_Bound_Ptr<Scheduler, ACE_Null_Mutex> scheduler(scheduler_ptr);

  if (scheduler->open () == -1)
    {
      ACE_ERROR_RETURN ((LM_ERROR,
                         ACE_TEXT ("(%t) Scheduler open failed...\n")),
                         -1);
    }

  {
    Printer *printer2 = 0;
    ACE_NEW_RETURN (printer2,
                    Printer ("I am printer 2"),
                    -1);

    // Ownership is transferred from the auto_ptr to the strong pointer.
    auto_ptr<Printer> a (printer2);
    Printer_var r (a);

    for (int i = 0; i < n_loops; i++)
      // Spawn off the methods, which run in a separate thread as
      // active object invocations.
      scheduler->print (r);
  }

  // Close things down.
  scheduler->end ();

  scheduler->wait ();

  ACE_DEBUG ((LM_DEBUG,
              ACE_TEXT ("(%t) Printer instance count is %d, expecting 0\n"),
              Printer::instance_count_));
  if (Printer::instance_count_ != 0)
    return -1;

#endif /* ACE_HAS_THREADS */
  ACE_END_TEST;

  return 0;
}
Beispiel #3
0
	int OBJ::ParseLine(int lineno,int argc,const char **argv)  // return TRUE to continue parsing, return FALSE to abort parsing process
	{
		int ret = 0;

		if ( argc >= 1 )
		{
			const char *foo = argv[0];
			if ( *foo != '#' )
			{
				if (strcmp(argv[0], "v") == 0 && argc == 4 )
				{
					float vx = (float) atof( argv[1] );
					float vy = (float) atof( argv[2] );
					float vz = (float) atof( argv[3] );
					Resize(mVerts, mMaxVerts, mNumVerts, mNumVerts + 3);
					mVerts[mNumVerts++] = vx;
					mVerts[mNumVerts++] = vy;
					mVerts[mNumVerts++] = vz;
				}
				else if (strcmp(argv[0],"vt") == 0 && (argc == 3 || argc == 4))
				{
					// ignore 4rd component if present
					float tx = (float) atof( argv[1] );
					float ty = (float) atof( argv[2] );
					Resize(mTexels, mMaxTexels, mNumTexels, mNumTexels + 2);
					mTexels[mNumTexels++] = tx;
					mTexels[mNumTexels++] = ty;
				}
				else if (strcmp(argv[0],"vn") == 0 && argc == 4 )
				{
					float normalx = (float) atof(argv[1]);
					float normaly = (float) atof(argv[2]);
					float normalz = (float) atof(argv[3]);
					Resize(mNormals, mMaxNormals, mNumNormals, mNumNormals + 3);
					mNormals[mNumNormals++] = normalx;
					mNormals[mNumNormals++] = normaly;
					mNormals[mNumNormals++] = normalz;

				}
				else if (strcmp(argv[0],"f") == 0 && argc >= 4 )
				{
					GeometryVertex v[32];

					int vcount = argc-1;

					for (int i=1; i<argc; i++)
					{
						GetVertex(v[i-1],argv[i] );
					}

					// need to generate a normal!
#if 0 // not currently implemented
					if ( mNormals.empty() )
					{
						Vector3d<float> p1( v[0].mPos );
						Vector3d<float> p2( v[1].mPos );
						Vector3d<float> p3( v[2].mPos );

						Vector3d<float> n;
						n.ComputeNormal(p3,p2,p1);

						for (int i=0; i<vcount; i++)
						{
							v[i].mNormal[0] = n.x;
							v[i].mNormal[1] = n.y;
							v[i].mNormal[2] = n.z;
						}

					}
#endif

					mCallback->NodeTriangle(&v[0],&v[1],&v[2], mTextured);

					if ( vcount >=3 ) // do the fan
					{
						for (int i=2; i<(vcount-1); i++)
						{
							mCallback->NodeTriangle(&v[0],&v[i],&v[i+1], mTextured);
						}
					}

				}
			}
		}

		return ret;
	}
Beispiel #4
0
int main()
{
  CGAL_KD_SETDTHREAD(11);  
  CGAL::set_pretty_mode ( std::cerr );
  CGAL_TEST_START;
  {
    typedef CGAL::Homogeneous_d<RT> Kernel;
    typedef CGAL::Convex_hull_d<Kernel> Convex_hull_d;
    typedef Convex_hull_d::Point_d Point;
    typedef Convex_hull_d::Hyperplane_d Plane;
    typedef Convex_hull_d::Simplex_handle Simplex_handle;
    typedef Convex_hull_d::Facet_handle Facet_handle;
    typedef Convex_hull_d::Vertex_handle Vertex_handle;

    Convex_hull_d T1(2);  
    const Convex_hull_d* pT1 = &T1;
    Point p1(0,0,1);
    Point p2(1,0,1);
    Point p3(0,1,1);
    Point p4(1,1,1);
    CGAL_TEST(T1.dimension()==2);
    CGAL_TEST(T1.current_dimension()==-1);
    Vertex_handle v1 = T1.insert(p1);
    CGAL_TEST(T1.associated_point(v1)==p1);
    T1.insert(p2);
    CGAL_TEST(T1.current_dimension()==1);
    CGAL_TEST(T1.is_dimension_jump(p3));
    T1.insert(p3);
    Simplex_handle s1 = T1.simplex(v1);
    int i1 = T1.index(v1);
    CGAL_TEST(T1.vertex_of_simplex(s1,i1)==v1);
    CGAL_TEST(T1.associated_point(T1.vertex_of_simplex(s1,1))==
              T1.point_of_simplex(s1,1));
    T1.insert(p3);
    CGAL_TEST((T1.opposite_simplex(T1.opposite_simplex(s1,1),
              T1.index_of_vertex_in_opposite_simplex(s1,1)) == s1));
    std::list<Simplex_handle> L = T1.all_simplices();
    CGAL_TEST(L.size() == 4);
    std::list<Facet_handle> F = T1.all_facets();
    CGAL_TEST(F.size() == 3);
    Facet_handle f1 = *(L.begin());
    CGAL_TEST(T1.associated_point(T1.vertex_of_facet(f1,1))==
              T1.point_of_facet(f1,1));
    CGAL_TEST((T1.opposite_facet(T1.opposite_facet(f1,1),
               T1.index_of_vertex_in_opposite_facet(f1,1)) == f1));
    Point pf0 = T1.point_of_facet(f1,0);
    Point pf1 = T1.point_of_facet(f1,1);
    Plane h = T1.hyperplane_supporting(f1);
    CGAL_TEST(h.has_on(pf0)&&h.has_on(pf1));
    std::list<Facet_handle> G = T1.facets_visible_from(p4);
    CGAL_TEST(G.size()==1);
    CGAL_TEST(T1.bounded_side(p4)==CGAL::ON_UNBOUNDED_SIDE && 
              T1.bounded_side(Point(1,1,10))==CGAL::ON_BOUNDED_SIDE);

    Convex_hull_d::Point_const_iterator   pit;
    Convex_hull_d::Vertex_iterator  vit;
    Convex_hull_d::Simplex_iterator sit;
    for (pit = T1.points_begin(); pit != T1.points_end(); pit++) *pit;
    for (vit = T1.vertices_begin(); vit != T1.vertices_end(); vit++) *vit;
    for (sit = T1.simplices_begin(); sit != T1.simplices_end(); sit++) *sit;
    T1.is_valid();
    T1.clear(2);
    CGAL_TEST(T1.number_of_vertices()==0);
    CGAL_TEST(T1.number_of_facets()==0);
    CGAL_TEST(T1.number_of_simplices()==0);
    std::vector<Point> V = make_vector(p1,p2,p3,p4);
    T1.initialize(V.begin(),V.end());
    Convex_hull_d::Facet_iterator fit;
    int fnum(0);
    for (fit = T1.facets_begin(); fit != T1.facets_end(); ++fnum, ++fit) *fit;
    CGAL_TEST(fnum==4);

#ifndef _MSC_VER // truncation due to name length exceeded
    Convex_hull_d::Hull_vertex_iterator hvit;
    int vnum(0);
    for (hvit = T1.hull_vertices_begin(); 
         hvit != T1.hull_vertices_end(); ++vnum, ++hvit) *hvit; 
    CGAL_TEST(vnum==4);

    Convex_hull_d::Facet_const_iterator fcit; 
    for (fcit = pT1->facets_begin(); fcit != pT1->facets_end(); ++fcit) *fcit;
    Convex_hull_d::Hull_vertex_const_iterator hvcit; 
    for (hvcit = pT1->hull_vertices_begin(); 
         hvcit != pT1->hull_vertices_end(); ++hvcit) *hvcit;
    Convex_hull_d::Hull_point_const_iterator hpcit; 
    for (hpcit = pT1->hull_points_begin(); 
         hpcit != pT1->hull_points_end(); ++hpcit) *hpcit;
#endif
  }


  {
    typedef CGAL::Cartesian<double> Kernel_3;
    typedef CGAL::Convex_hull_d_traits_3<Kernel_3> Kernel;
    typedef CGAL::Convex_hull_d<Kernel> Convex_hull_d;
    typedef Convex_hull_d::Point_d Point;
    typedef Convex_hull_d::Hyperplane_d Plane;
    typedef Convex_hull_d::Simplex_handle Simplex_handle;
    typedef Convex_hull_d::Facet_handle Facet_handle;
    typedef Convex_hull_d::Vertex_handle Vertex_handle;
    Convex_hull_d T2(3);  
    Point p1(0,0,0,1);
    Point p2(1,0,0,1);
    Point p3(0,1,0,1);
    Point p4(0,0,1,1);
    Point p5(1,1,1,1);
    CGAL_TEST(T2.dimension()==3);
    CGAL_TEST(T2.current_dimension()==-1);
    T2.insert(p1);
    T2.insert(p2);
    CGAL_TEST(T2.is_dimension_jump(p3));
    T2.insert(p3);
    CGAL_TEST(T2.current_dimension()==2);
    CGAL_TEST(T2.is_dimension_jump(p4));
    Vertex_handle v1 = T2.insert(p4);
    CGAL_TEST(T2.associated_point(v1)==p4);

    Simplex_handle s1 = T2.simplex(v1);
    int i1 = T2.index(v1);


    CGAL_TEST(T2.vertex_of_simplex(s1,i1)==v1);
    CGAL_TEST(T2.associated_point(T2.vertex_of_simplex(s1,1))==
          T2.point_of_simplex(s1,1));
    CGAL_TEST((T2.opposite_simplex(T2.opposite_simplex(s1,1),
               T2.index_of_vertex_in_opposite_simplex(s1,1)) == s1));

    std::list<Simplex_handle> L = T2.all_simplices();
    CGAL_TEST(L.size() == 5);
    std::list<Facet_handle> F = T2.all_facets();
    CGAL_TEST(F.size() == 4);
    Facet_handle f1 = *(L.begin());
    CGAL_TEST(T2.associated_point(T2.vertex_of_facet(f1,1))==
              T2.point_of_facet(f1,1));
    CGAL_TEST((T2.opposite_facet(T2.opposite_facet(f1,1),
               T2.index_of_vertex_in_opposite_facet(f1,1)) == f1));

    Point pf0 = T2.point_of_facet(f1,0);
    Point pf1 = T2.point_of_facet(f1,1);
    Point pf2 = T2.point_of_facet(f1,2);
    Plane h = T2.hyperplane_supporting(f1);
    CGAL_TEST(h.has_on(pf0)&&h.has_on(pf1)&&h.has_on(pf2));

    std::list<Facet_handle> G = T2.facets_visible_from(p5);
    CGAL_TEST(G.size()==1);
    CGAL_TEST(T2.bounded_side(p5)==CGAL::ON_UNBOUNDED_SIDE && 
              T2.bounded_side(Point(1,1,1,10))==CGAL::ON_BOUNDED_SIDE);
    T2.is_valid();
    T2.clear(3);


  }


  {
    typedef CGAL::Homogeneous<RT> Kernel_3;
    typedef CGAL::Convex_hull_d_traits_3<Kernel_3> Kernel;
    typedef CGAL::Convex_hull_d<Kernel> Convex_hull_d;
    typedef Convex_hull_d::Point_d Point;
    typedef Convex_hull_d::Hyperplane_d Plane;
    typedef Convex_hull_d::Simplex_handle Simplex_handle;
    typedef Convex_hull_d::Facet_handle Facet_handle;
    typedef Convex_hull_d::Vertex_handle Vertex_handle;
    Convex_hull_d T2(3);  
    Point p1(0,0,0,1);
    Point p2(1,0,0,1);
    Point p3(0,1,0,1);
    Point p4(0,0,1,1);
    Point p5(1,1,1,1);
    CGAL_TEST(T2.dimension()==3);
    CGAL_TEST(T2.current_dimension()==-1);
    T2.insert(p1);
    T2.insert(p2);
    CGAL_TEST(T2.is_dimension_jump(p3));
    T2.insert(p3);
    CGAL_TEST(T2.current_dimension()==2);
    CGAL_TEST(T2.is_dimension_jump(p4));
    Vertex_handle v1 = T2.insert(p4);
    CGAL_TEST(T2.associated_point(v1)==p4);

    Simplex_handle s1 = T2.simplex(v1);
    int i1 = T2.index(v1);


    CGAL_TEST(T2.vertex_of_simplex(s1,i1)==v1);
    CGAL_TEST(T2.associated_point(T2.vertex_of_simplex(s1,1))==
          T2.point_of_simplex(s1,1));
    CGAL_TEST((T2.opposite_simplex(T2.opposite_simplex(s1,1),
               T2.index_of_vertex_in_opposite_simplex(s1,1)) == s1));

    std::list<Simplex_handle> L = T2.all_simplices();
    CGAL_TEST(L.size() == 5);
    std::list<Facet_handle> F = T2.all_facets();
    CGAL_TEST(F.size() == 4);
    Facet_handle f1 = *(L.begin());
    CGAL_TEST(T2.associated_point(T2.vertex_of_facet(f1,1))==
              T2.point_of_facet(f1,1));
    CGAL_TEST((T2.opposite_facet(T2.opposite_facet(f1,1),
               T2.index_of_vertex_in_opposite_facet(f1,1)) == f1));

    Point pf0 = T2.point_of_facet(f1,0);
    Point pf1 = T2.point_of_facet(f1,1);
    Point pf2 = T2.point_of_facet(f1,2);
    Plane h = T2.hyperplane_supporting(f1);
    CGAL_TEST(h.has_on(pf0)&&h.has_on(pf1)&&h.has_on(pf2));

    std::list<Facet_handle> G = T2.facets_visible_from(p5);
    CGAL_TEST(G.size()==1);
    CGAL_TEST(T2.bounded_side(p5)==CGAL::ON_UNBOUNDED_SIDE && 
              T2.bounded_side(Point(1,1,1,10))==CGAL::ON_BOUNDED_SIDE);
    T2.is_valid();
    T2.clear(3);


  }
  {
    typedef CGAL::Cartesian_d<double> Kernel;
    typedef CGAL::Convex_hull_d<Kernel> Convex_hull_d;
    typedef Convex_hull_d::Point_d Point;
    typedef Convex_hull_d::Hyperplane_d Plane;
    typedef Convex_hull_d::Simplex_handle Simplex_handle;
    typedef Convex_hull_d::Facet_handle Facet_handle;
    typedef Convex_hull_d::Vertex_handle Vertex_handle;
    Convex_hull_d T2(3);  
    Point p1(0,0,0,1);
    Point p2(1,0,0,1);
    Point p3(0,1,0,1);
    Point p4(0,0,1,1);
    Point p5(1,1,1,1);
    CGAL_TEST(T2.dimension()==3);
    CGAL_TEST(T2.current_dimension()==-1);
    T2.insert(p1);
    T2.insert(p2);
    CGAL_TEST(T2.is_dimension_jump(p3));
    T2.insert(p3);
    CGAL_TEST(T2.current_dimension()==2);
    CGAL_TEST(T2.is_dimension_jump(p4));
    Vertex_handle v1 = T2.insert(p4);
    CGAL_TEST(T2.associated_point(v1)==p4);

    Simplex_handle s1 = T2.simplex(v1);
    int i1 = T2.index(v1);


    CGAL_TEST(T2.vertex_of_simplex(s1,i1)==v1);
    CGAL_TEST(T2.associated_point(T2.vertex_of_simplex(s1,1))==
          T2.point_of_simplex(s1,1));
    CGAL_TEST((T2.opposite_simplex(T2.opposite_simplex(s1,1),
               T2.index_of_vertex_in_opposite_simplex(s1,1)) == s1));

    std::list<Simplex_handle> L = T2.all_simplices();
    CGAL_TEST(L.size() == 5);
    std::list<Facet_handle> F = T2.all_facets();
    CGAL_TEST(F.size() == 4);
    Facet_handle f1 = *(L.begin());
    CGAL_TEST(T2.associated_point(T2.vertex_of_facet(f1,1))==
              T2.point_of_facet(f1,1));
    CGAL_TEST((T2.opposite_facet(T2.opposite_facet(f1,1),
               T2.index_of_vertex_in_opposite_facet(f1,1)) == f1));

    Point pf0 = T2.point_of_facet(f1,0);
    Point pf1 = T2.point_of_facet(f1,1);
    Point pf2 = T2.point_of_facet(f1,2);
    Plane h = T2.hyperplane_supporting(f1);
    CGAL_TEST(h.has_on(pf0)&&h.has_on(pf1)&&h.has_on(pf2));

    std::list<Facet_handle> G = T2.facets_visible_from(p5);
    CGAL_TEST(G.size()==1);
    CGAL_TEST(T2.bounded_side(p5)==CGAL::ON_UNBOUNDED_SIDE && 
              T2.bounded_side(Point(1,1,1,10))==CGAL::ON_BOUNDED_SIDE);
    T2.is_valid();
    T2.clear(3);


  }
  {
    typedef CGAL::Homogeneous_d<RT> Kernel;
    typedef CGAL::Convex_hull_d<Kernel> Convex_hull_d;
    typedef Convex_hull_d::Point_d Point;
    typedef Convex_hull_d::Hyperplane_d Plane;
    typedef Convex_hull_d::Simplex_handle Simplex_handle;
    typedef Convex_hull_d::Facet_handle Facet_handle;
    typedef Convex_hull_d::Vertex_handle Vertex_handle;
    Convex_hull_d T2(3);  
    Point p1(0,0,0,1);
    Point p2(1,0,0,1);
    Point p3(0,1,0,1);
    Point p4(0,0,1,1);
    Point p5(1,1,1,1);
    CGAL_TEST(T2.dimension()==3);
    CGAL_TEST(T2.current_dimension()==-1);
    T2.insert(p1);
    T2.insert(p2);
    CGAL_TEST(T2.is_dimension_jump(p3));
    T2.insert(p3);
    CGAL_TEST(T2.current_dimension()==2);
    CGAL_TEST(T2.is_dimension_jump(p4));
    Vertex_handle v1 = T2.insert(p4);
    CGAL_TEST(T2.associated_point(v1)==p4);

    Simplex_handle s1 = T2.simplex(v1);
    int i1 = T2.index(v1);


    CGAL_TEST(T2.vertex_of_simplex(s1,i1)==v1);
    CGAL_TEST(T2.associated_point(T2.vertex_of_simplex(s1,1))==
          T2.point_of_simplex(s1,1));
    CGAL_TEST((T2.opposite_simplex(T2.opposite_simplex(s1,1),
               T2.index_of_vertex_in_opposite_simplex(s1,1)) == s1));

    std::list<Simplex_handle> L = T2.all_simplices();
    CGAL_TEST(L.size() == 5);
    std::list<Facet_handle> F = T2.all_facets();
    CGAL_TEST(F.size() == 4);
    Facet_handle f1 = *(L.begin());
    CGAL_TEST(T2.associated_point(T2.vertex_of_facet(f1,1))==
              T2.point_of_facet(f1,1));
    CGAL_TEST((T2.opposite_facet(T2.opposite_facet(f1,1),
               T2.index_of_vertex_in_opposite_facet(f1,1)) == f1));

    Point pf0 = T2.point_of_facet(f1,0);
    Point pf1 = T2.point_of_facet(f1,1);
    Point pf2 = T2.point_of_facet(f1,2);
    Plane h = T2.hyperplane_supporting(f1);
    CGAL_TEST(h.has_on(pf0)&&h.has_on(pf1)&&h.has_on(pf2));

    std::list<Facet_handle> G = T2.facets_visible_from(p5);
    CGAL_TEST(G.size()==1);
    CGAL_TEST(T2.bounded_side(p5)==CGAL::ON_UNBOUNDED_SIDE && 
              T2.bounded_side(Point(1,1,1,10))==CGAL::ON_BOUNDED_SIDE);
    T2.is_valid();
    T2.clear(3);


  }
  CGAL_TEST_END;
}
/**
* Draw a cube into the verticies buffer. Draws the cube in the x-z plane at 
* the specified row and column with a set height and color.
*
* In most cases, the texture coordinates are the same as the offsets for the cube
* vertex coordinates. Minor exception for left and right side to ensure texture
* is not sideways.
*
* @param x coordinate location
* @param y coordinate location
* @param z coordinate location
* @param size cube scaling size
* @param side cube side to draw
* @param type tile type to draw
*/
void WorldNode::DrawTile(float x, float y, float z, float s, CubeSide side, TileType type)
{
    D3DXVECTOR3 n; // normal

    switch(side)
    {

    case kTop:
    {
        D3DXVECTOR3 p1( x,   y+s, z   );
        D3DXVECTOR3 p2( x,   y+s, z+s );
        D3DXVECTOR3 p3( x+s, y+s, z+s );
        D3DXVECTOR3 p4( x+s, y+s, z   );
        D3DXVec3Cross(&n, &(p2-p1), &(p3-p1));
        AddPlane(
            CustomVertex( p1, n, D3DXVECTOR2(0.0f, 1.0f) ),
            CustomVertex( p2, n, D3DXVECTOR2(0.0f, 0.0f) ),
            CustomVertex( p3, n, D3DXVECTOR2(1.0f, 0.0f) ),
            type);
        AddPlane(
            CustomVertex( p1, n, D3DXVECTOR2(0.0f, 1.0f) ),
            CustomVertex( p3, n, D3DXVECTOR2(1.0f, 0.0f) ),
            CustomVertex( p4, n, D3DXVECTOR2(1.0f, 1.0f) ),
            type);
        m_vCollQuads.push_back( CollQuad(p1, p2, p3, p4, n) ); 
        break;
    }
    case kBottom:
    {
        D3DXVECTOR3 p1( x,   y,   z   );
        D3DXVECTOR3 p2( x,   y,   z+s );
        D3DXVECTOR3 p3( x+s, y,   z+s );
        D3DXVECTOR3 p4( x+s, y,   z   );
        D3DXVec3Cross(&n, &(p2-p1), &(p3-p1));
        AddPlane(
            CustomVertex( p1, n, D3DXVECTOR2(0.0f, 1.0f) ),
            CustomVertex( p2, n, D3DXVECTOR2(0.0f, 0.0f) ),
            CustomVertex( p3, n, D3DXVECTOR2(1.0f, 0.0f) ),
            type);
        AddPlane(
            CustomVertex( p1, n, D3DXVECTOR2(0.0f, 1.0f) ),
            CustomVertex( p3, n, D3DXVECTOR2(1.0f, 0.0f) ),
            CustomVertex( p4, n, D3DXVECTOR2(1.0f, 1.0f) ),
            type);
        m_vCollQuads.push_back( CollQuad(p1, p2, p3, p4, n) ); 
        break;
    }
    case kLeft:        
    {
        D3DXVECTOR3 p1( x,   y,   z   );
        D3DXVECTOR3 p2( x,   y,   z+s );
        D3DXVECTOR3 p3( x,   y+s, z+s );
        D3DXVECTOR3 p4( x,   y+s, z   );
        D3DXVec3Cross(&n, &(p2-p1), &(p3-p1));
        AddPlane(
            CustomVertex( p1, n, D3DXVECTOR2(1.0f, 1.0f) ),
            CustomVertex( p2, n, D3DXVECTOR2(0.0f, 1.0f) ), 
            CustomVertex( p3, n, D3DXVECTOR2(0.0f, 0.0f) ),
            type);
        AddPlane(
            CustomVertex( p1, n, D3DXVECTOR2(1.0f, 1.0f) ),
            CustomVertex( p3, n, D3DXVECTOR2(0.0f, 0.0f) ),
            CustomVertex( p4, n, D3DXVECTOR2(1.0f, 0.0f) ),
            type);
        m_vCollQuads.push_back( CollQuad(p1, p2, p3, p4, n) ); 
        break;
    }
    case kRight:
    {
        D3DXVECTOR3 p1( x+s, y,    z   );
        D3DXVECTOR3 p2( x+s, y+s,  z   );
        D3DXVECTOR3 p3( x+s, y+s,  z+s );
        D3DXVECTOR3 p4( x+s, y,    z+s );
        D3DXVec3Cross(&n, &(p2-p1), &(p3-p1));
        AddPlane(
            CustomVertex( p1, n, D3DXVECTOR2(0.0f, 1.0f) ),
            CustomVertex( p2, n, D3DXVECTOR2(0.0f, 0.0f) ),
            CustomVertex( p3, n, D3DXVECTOR2(1.0f, 0.0f) ),
            type);
        AddPlane(
            CustomVertex( p1, n, D3DXVECTOR2(0.0f, 1.0f) ),
            CustomVertex( p3, n, D3DXVECTOR2(1.0f, 0.0f) ),
            CustomVertex( p4, n, D3DXVECTOR2(1.0f, 1.0f) ),
            type);
        m_vCollQuads.push_back( CollQuad(p1, p2, p3, p4, n) ); 
        break;
    }
    case kUpper:
    {
        D3DXVECTOR3 p1( x,   y,   z+s );
        D3DXVECTOR3 p2( x+s, y,   z+s );
        D3DXVECTOR3 p3( x+s, y+s, z+s );
        D3DXVECTOR3 p4( x,   y+s, z+s );
        D3DXVec3Cross(&n, &(p2-p1), &(p3-p1));
        AddPlane(
            CustomVertex( p1, n, D3DXVECTOR2(1.0f, 1.0f) ),
            CustomVertex( p2, n, D3DXVECTOR2(0.0f, 1.0f) ),
            CustomVertex( p3, n, D3DXVECTOR2(0.0f, 0.0f) ),
            type);
        AddPlane(
            CustomVertex( p1, n, D3DXVECTOR2(1.0f, 1.0f) ),
            CustomVertex( p3, n, D3DXVECTOR2(0.0f, 0.0f) ),
            CustomVertex( p4, n, D3DXVECTOR2(1.0f, 0.0f) ),
            type);
        m_vCollQuads.push_back( CollQuad(p1, p2, p3, p4, n) ); 
        break;
    }
    case kLower:
    {
        D3DXVECTOR3 p1( x,   y,   z   );
        D3DXVECTOR3 p2( x,   y+s, z   );
        D3DXVECTOR3 p3( x+s, y+s, z   );
        D3DXVECTOR3 p4( x+s, y,   z   );
        D3DXVec3Cross(&n, &(p2-p1), &(p3-p1));
        AddPlane(
            CustomVertex( p1, n, D3DXVECTOR2(0.0f, 1.0f) ),
            CustomVertex( p2, n, D3DXVECTOR2(0.0f, 0.0f) ),
            CustomVertex( p3, n, D3DXVECTOR2(1.0f, 0.0f) ),
            type);
        AddPlane(
            CustomVertex( p1, n, D3DXVECTOR2(0.0f, 1.0f) ),
            CustomVertex( p3, n, D3DXVECTOR2(1.0f, 0.0f) ),
            CustomVertex( p4, n, D3DXVECTOR2(1.0f, 1.0f) ),
            type);
        m_vCollQuads.push_back( CollQuad(p1, p2, p3, p4, n) ); 
        break;
    }
    default:
        break;
    }
}
Beispiel #6
0
void test_RT()
{
  typedef RT                 Cls;

  //  _test_cls_regular_3( Cls() );
  typedef traits::Bare_point Point;
  typedef traits::Weighted_point Weighted_point;

  typedef typename Cls::Vertex_handle                Vertex_handle;
  typedef typename Cls::Cell_handle                  Cell_handle; 
  typedef typename Cls::Facet                        Facet;
  typedef typename Cls::Edge                         Edge;
  
  typedef std::list<Weighted_point>                  list_point;
  typedef typename Cls::Finite_cells_iterator        Finite_cells_iterator;

  // temporary version

  int n, m;
  int count = 0;

  // For dimension 0, we need to check that the point of highest weight is the
  // one that finally ends up in the vertex.
  std::cout << " test dimension 0 " << std::endl;
  Cls T0;
  T0.insert(Weighted_point( Point (0,0,0), 0) );
  T0.insert(Weighted_point( Point (0,0,0), 1) );
  T0.insert(Weighted_point( Point (0,0,0), -1) );
  assert(T0.dimension() == 0);
  assert(T0.number_of_vertices() == 1);
  assert(T0.finite_vertices_begin()->point().weight() == 1);

  std::cout << " test dimension 1 " << std::endl;
  Cls T1;
  std::cout << " number of inserted points : " ;
  Weighted_point p[5];
  for ( m=0; m<5; m++) {
    if ( (m%2)== 0 ) 
      p[m] = Weighted_point( Point( 2*m,0,0 ), 2 );
    else 
      p[m] = Weighted_point( Point( -2*m+1,0,0 ), 2 );
    T1.insert( p[m] );
    count++;
    if (count <10)
      std::cout << count << '\b' ;
    else
      if (count < 100)
	std::cout << count << '\b' << '\b' ;
      else
	std::cout << count << '\b' << '\b' << '\b' ;
    std::cout.flush();
  }
  assert( T1.is_valid() );
  std::cout << std::endl << " number of vertices : " 
      << T1.number_of_vertices() << std::endl;

  std::cout << " number of inserted points : " ;
  Weighted_point q[5];
  for ( m=0; m<5; m++) {
    if ( (m%2)== 0 )
      q[m] = Weighted_point( Point( 2*m+1,0,0 ), 5 );
    else 
      q[m] = Weighted_point( Point( -2*m+1,0,0 ), 5 );
    T1.insert( q[m] );
    count++;
    if (count <10)
      std::cout << count << '\b' ;
    else
      if (count < 100)
  std::cout << count << '\b' << '\b' ;
      else
  std::cout << count << '\b' << '\b' << '\b' ;
    std::cout.flush();  
  }
  assert( T1.is_valid() );
  std::cout << std::endl << " number of vertices : " 
      << T1.number_of_vertices() << std::endl;

  std::cout << " number of inserted points : " ;
  Weighted_point r[10];
  for ( m=0; m<10; m++) {
    if ( (m%2)== 0 ) 
      r[m] = Weighted_point( Point( m,0,0 ), 1 );
    else 
      r[m] = Weighted_point( Point( -m,0,0 ), 1 );
    T1.insert( r[m] );
    count++;
    if (count <10)
      std::cout << count << '\b' ;
    else
      if (count < 100)
  std::cout << count << '\b' << '\b' ;
      else
  std::cout << count << '\b' << '\b' << '\b' ;
    std::cout.flush();  
  }
  assert( T1.is_valid() );
  std::cout << std::endl << " number of vertices : " 
      << T1.number_of_vertices() << std::endl;
  assert( T1.dimension()==1 );

  // The following is distilled from a bug report by Wulue Zhao
  // ([email protected]), a student of Tamal Dey.
  Point pt0(0,0,0);
  Point pt1( 1,0,0), pt2(2,0,0),  pt3(3,0,0);
  Point pt4(-1,0,0), pt5(-2,0,0), pt6(-3,0,0);

  Weighted_point wp0(pt0,10.0);
  Weighted_point wp1(pt1,0.0),  wp2(pt2,0.0),  wp3(pt3,0.0);
  Weighted_point wp4(pt4,0.0),  wp5(pt5,0.0),  wp6(pt6,0.0);

  Cls T11;

  T11.insert(wp0);
  T11.insert(wp1);
  T11.insert(wp2);
  T11.insert(wp3);
  T11.insert(wp4);
  T11.insert(wp5);
  T11.insert(wp6);

  assert(T11.is_valid());

  // And another distilled bug report from the same guy.
 {
  Point p1(-0.07, 0.04, 0.04);
  Point p2(0.09, 0.04, 0.04);
  Point p3(0.09, -0.05, 0.04);
  Point p4(0.05, -0.05, 0.04);
  Point p5(0.05, 0.0, 0.04);
  Point p6(-0.07, 0.0, 0.04);
  Point p7(-0.07, 0.04, -0.04);
  Point p8(0.09, 0.04, -0.04);
  Point p9(0.09, -0.05, -0.04);
  Point p10(0.05, -0.05, -0.04);
  Point p11(0.05, 0.0, -0.04);
  Point p12(-0.07, 0.0, -0.04);

  Weighted_point wp1(p1,0);
  Weighted_point wp2(p2,0);
  Weighted_point wp3(p3,0);
  Weighted_point wp4(p4,0);
  Weighted_point wp5(p5,0);
  Weighted_point wp6(p6,0);
  Weighted_point wp7(p7,0);
  Weighted_point wp8(p8,0);
  Weighted_point wp9(p9,0);
  Weighted_point wp10(p10,0);
  Weighted_point wp11(p11,0);
  Weighted_point wp12(p12,0);
  Weighted_point wp13(p3,0.3); // wp13 has the same coordinates with wp3

  Cls T111;

  T111.insert(wp1);
  T111.insert(wp2);
  T111.insert(wp3);
  T111.insert(wp13); // it doesnot work inserting wp13 here
  T111.insert(wp4);
  T111.insert(wp5);
  T111.insert(wp6);
  T111.insert(wp7);
  T111.insert(wp8);
  T111.insert(wp9);
  T111.insert(wp10);
  T111.insert(wp11);
  T111.insert(wp12);

  assert(T111.is_valid());
 }

  std::cout << " test dimension 2 " << std::endl;
  std::cout << " number of inserted points : " ;
  Cls T2;

  count = 0 ;
  int px=1, py=1;
  int qx=-1, qy=2;
  Weighted_point s[400];
  for (m=0; m<10; m++)
    for (n=0; n<10; n++) {
      s[m+20*n] = Weighted_point( Point(m*px+n*qx, m*py+n*qy, 0), 1 );
      T2.insert( s[m+20*n] );
      count++;
      if (count <10)
  std::cout << count << '\b' ;
      else
  if (count < 100)
    std::cout << count << '\b' << '\b' ;
  else
    std::cout << count << '\b' << '\b' << '\b' ;
      std::cout.flush();
    }
  for (m=10; m<20; m++)
    for (n=0; n<10; n++) {
      s[m+20*n] = Weighted_point( Point(m*px+n*qx, m*py+n*qy, 0), -1 );
      T2.insert( s[m+20*n] );
      count++;
      if (count <10)
  std::cout << count << '\b' ;
      else
  if (count < 100)
    std::cout << count << '\b' << '\b' ;
  else
    std::cout << count << '\b' << '\b' << '\b' ;
      std::cout.flush();
    }
  for (m=0; m<10; m++)
    for (n=10; n<20; n++) {
      s[m+20*n] = Weighted_point( Point(m*px+n*qx, m*py+n*qy, 0), -2 );
      T2.insert( s[m+20*n] );
      count++;
      if (count <10)
  std::cout << count << '\b' ;
      else
  if (count < 100)
    std::cout << count << '\b' << '\b' ;
  else
    std::cout << count << '\b' << '\b' << '\b' ;
      std::cout.flush();
    }
  for (m=10; m<20; m++)
    for (n=10; n<20; n++) {
      s[m+20*n] = Weighted_point( Point(m*px+n*qx, m*py+n*qy, 0), 5 );
      T2.insert( s[m+20*n] );
      count++;
      if (count <10)
  std::cout << count << '\b' ;
      else
  if (count < 100)
    std::cout << count << '\b' << '\b' ;
  else
    std::cout << count << '\b' << '\b' << '\b' ;
      std::cout.flush();
    }
 
  std::cout << std::endl << " number of vertices : " 
      << T2.number_of_vertices() << std::endl;
  assert( T2.dimension()==2 );
  assert( T2.is_valid() );

 // dimension 3
  std::cout << " test dimension 3" << std::endl;
  Cls T;

  list_point lp;
  int a, b, d;
  for (a=0;a!=10;a++)
    //    for (b=0;b!=10;b++)
    for (b=0;b!=5;b++)
      //      for (d=0;d!=10;d++)
      for (d=0;d!=5;d++)
  lp.push_back(Weighted_point( Point(a*b-d*a + (a-b)*10 +a ,
             a-b+d +5*b,
             a*a-d*d+b),
             a*b-a*d) );
  list_point::iterator it;
  count = 0 ;
  std::cout << " number of inserted points : " ;
  for (it=lp.begin(); it!=lp.end(); ++it){
    count++;
    T.insert(*it);
    if (count <10)
      std::cout << count << '\b' ;
    else
      if (count < 100)
        std::cout << count << '\b' << '\b' ;
      else 
        if (count < 1000)
          std::cout << count << '\b' << '\b' << '\b' ;
        else
    std::cout << count << std::endl;
    std::cout.flush();
  }
  std::cout << std::endl;

  std::cout << " number of vertices : " 
      << T.number_of_vertices() << std::endl;
  assert(T.is_valid());
  assert(T.dimension()==3);

  T.clear();
  std::cout << " test iterator range insert" << std::endl;
  T.insert (lp.begin(), lp.end());

  std::cout << " number of vertices : " 
      << T.number_of_vertices() << std::endl;
  assert(T.is_valid());
  assert(T.dimension()==3);


    //test nearest_power_vertex
  std::cout << " test nearest_power_vertex " << std::endl;
  Point pp1(0.0, 0.0, 0.0);
  Point pp2(1.0, 0.0, 0.0);
  Point pp3(0.0, 1.0, 0.0);
  Point pp4(0.0, 0.0, 1.0);
  Point pp5(1.0, 1.0, 0.0);
  Point pp6(0.0, 1.0, 1.0);
  Point pp7(1.0, 0.0, 1.0);
  Point pp8(1.0, 1.0, 1.0);

  Weighted_point wpp1(pp1, 1.0);
  Weighted_point wpp2(pp2, 2.0);
  Weighted_point wpp3(pp3, 1.0);
  Weighted_point wpp4(pp4, 4.0);
  Weighted_point wpp5(pp5, 1.0);
  Weighted_point wpp6(pp6, 1.0);
  Weighted_point wpp7(pp7, 1.0);
  Weighted_point wpp8(pp8, 8.0);

  Cls T3;

  T3.insert(wpp1);
  Vertex_handle v2 = T3.insert(wpp2);
  assert( T3.nearest_power_vertex(Point(0.5,0.5,0.5)) == v2);
  
  T3.insert(wpp3);
  Vertex_handle v4 = T3.insert(wpp4);
  assert( T3.nearest_power_vertex(Point(0.5,0.5,0.5)) == v4);

  T3.insert(wpp5);
  T3.insert(wpp6);
  T3.insert(wpp7);
  // Avoid inserting the same point twice, now that hidden points are handled,
  // insert (existing_point) returns Vertex_handle().
  // T3.insert(wpp8);
  Vertex_handle v8 = T3.insert(wpp8);
  Point query(0.5,0.5,0.5);
  assert(T3.nearest_power_vertex(query) == v8);
  assert(T3.nearest_power_vertex(Weighted_point(query,1.0)) == v8 );
  assert(T3.nearest_power_vertex_in_cell(query ,v8->cell()) == v8); 
  
  // test dual
  std::cout << " test dual member functions" << std::endl;
  Finite_cells_iterator fcit = T3.finite_cells_begin();
  for( ; fcit != T3.finite_cells_end(); ++fcit) {
    Point cc = T3.dual(fcit);
    Vertex_handle ncc = T3.nearest_power_vertex(cc);
    assert(fcit->has_vertex(ncc));
  }

  // test Gabriel
  std::cout << " test is_Gabriel " << std::endl;
  Point q0(0.,0.,0.);
  Point q1(2.,0.,0.);
  Point q2(0.,2.,0.);
  Point q3(0.,0.,2.);

  Weighted_point wq0(q0,0.);
  Weighted_point wq1(q1,0.);
  Weighted_point wq2(q2,0.);
  Weighted_point wq3(q3,0.);
  Weighted_point wq01(q0,2.);
  
  Cls T4;
  Vertex_handle v0 = T4.insert(wq0);
  Vertex_handle v1 = T4.insert(wq1);
  v2 = T4.insert(wq2);
  Vertex_handle v3 = T4.insert(wq3);
  Cell_handle c;
  int i,j,k,l;
  assert(T4.is_facet(v0,v1,v2,c,j,k,l));
  i = 6 - (j+k+l);
  Facet f = std::make_pair(c,i);
  assert(T4.is_Gabriel(c,i));
  assert(T4.is_Gabriel(f));
  assert(T4.is_facet(v1,v2,v3,c,j,k,l));
  i = 6 - (j+k+l);
  assert(!T4.is_Gabriel(c,i));
  assert(T4.is_edge(v0,v1,c,i,j));
  assert(T4.is_Gabriel(c,i,j));
  Edge e = make_triple(c,i,j);
  assert(T4.is_Gabriel(e));
  assert(T4.is_edge(v2,v3,c,i,j));
  assert(T4.is_Gabriel(c,i,j));
  
  Vertex_handle v01 = T4.insert(wq01);
  (void) v01; // kill warning
  assert(T4.is_edge(v2,v3,c,i,j));
  assert(!T4.is_Gabriel(c,i,j));

  Weighted_point wwq0(q0,0.);
  Weighted_point wwq1(q1,0.);
  Weighted_point wwq2(q2,0.);
  Weighted_point wwq3(q3,5.);
  Cls T5;
  v0 = T5.insert(wwq0);
  v1 = T5.insert(wwq1);
  v2 = T5.insert(wwq2);
  v3 = T5.insert(wwq3);
  assert(T5.nearest_power_vertex(v3->point().point()) == v3);
  assert(T5.nearest_power_vertex(v0->point().point()) == v3);
  assert(T5.is_Gabriel(v3));
  assert(!T5.is_Gabriel(v0));
}
Beispiel #7
0
int main(int argc, char **argv)
{
  plan_tests(41);

  FlatPoint p1(fixed_one, fixed_one);
  FlatPoint p2(fixed_one, fixed_two);
  FlatPoint p3(fixed(3), fixed_ten);

  // test cross()
  ok1(equals(p1.CrossProduct(p2), 1));
  ok1(equals(p2.CrossProduct(p1), -1));
  ok1(equals(p1.CrossProduct(p3), 7));
  ok1(equals(p3.CrossProduct(p1), -7));
  ok1(equals(p2.CrossProduct(p3), 4));
  ok1(equals(p3.CrossProduct(p2), -4));

  // test mul_y()
  p2.MultiplyY(fixed_two);
  ok1(equals(p2.x, 1));
  ok1(equals(p2.y, 4));

  // test sub()
  p2.Subtract(p1);
  ok1(equals(p2.x, 0));
  ok1(equals(p2.y, 3));

  // test add()
  p2.Add(p3);
  ok1(equals(p2.x, 3));
  ok1(equals(p2.y, 13));

  // test rotate()
  p2.Rotate(Angle::Degrees(fixed(-90)));
  ok1(equals(p2.x, 13));
  ok1(equals(p2.y, -3));

  p2.Rotate(Angle::Degrees(fixed(45)));
  p2.Rotate(Angle::Degrees(fixed(45)));
  ok1(equals(p2.x, 3));
  ok1(equals(p2.y, 13));

  // test d()
  ok1(equals(p2.Distance(p3), 3));
  ok1(equals(p3.Distance(p2), 3));

  // test mag_sq()
  ok1(equals(p1.MagnitudeSquared(), 2));
  ok1(equals(p2.MagnitudeSquared(), 178));
  ok1(equals(p3.MagnitudeSquared(), 109));

  // test mag()
  ok1(equals(p1.Magnitude(), 1.4142135623730950488016887242097));
  ok1(equals(p2.Magnitude(), 13.341664064126333712489436272508));
  ok1(equals(p3.Magnitude(), 10.440306508910550179757754022548));

  // test dot()
  ok1(equals(p1.DotProduct(p2), 16));
  ok1(equals(p2.DotProduct(p1), 16));
  ok1(equals(p1.DotProduct(p3), 13));
  ok1(equals(p3.DotProduct(p1), 13));
  ok1(equals(p2.DotProduct(p3), 139));
  ok1(equals(p3.DotProduct(p2), 139));

  // test ==
  ok1(p1 == p1);
  ok1(p2 == p2);
  ok1(p3 == p3);
  /*
  // Test #2 fails due to floating point inaccuracies
  ok1(p1 == FlatPoint(fixed_one, fixed_one));
  ok1(p2 == FlatPoint(fixed(3), fixed(13)));
  ok1(p3 == FlatPoint(fixed(3), fixed_ten));
  */

  // test *
  p2 = p3 * fixed(1.5);
  ok1(equals(p2.x, 4.5));
  ok1(equals(p2.y, 15));

  // test +
  p2 = p1 + p3;
  ok1(equals(p2.x, 4));
  ok1(equals(p2.y, 11));

  // test +=
  p2 += p1;
  ok1(equals(p2.x, 5));
  ok1(equals(p2.y, 12));

  // test -
  p2 = p3 - p1;
  ok1(equals(p2.x, 2));
  ok1(equals(p2.y, 9));

  return exit_status();
}
Beispiel #8
0
CubitStatus
SimplifyTool::weighted_average_normal(RefFace* ref_face,
                                      CubitVector &normal, 
                                      double &weight )
{
    GMem g_mem;
    unsigned short norm_tol = 30;
    double dist_tol = -1.0;

    ref_face->get_geometry_query_engine()->
        get_graphics(ref_face->get_surface_ptr(), &g_mem, norm_tol, dist_tol );

    if(g_mem.fListCount < 1)
    {
        // Decrease tolerance and try again (we can get this for small features)
        norm_tol /= 2;
        ref_face->get_geometry_query_engine()->
            get_graphics(ref_face->get_surface_ptr(), &g_mem, norm_tol, dist_tol );
    }

    if(g_mem.fListCount < 1)
    {
        // Lets give up 
        PRINT_ERROR( "Unable to find average normal of a surface\n" );
        return CUBIT_FAILURE;
    }

    // Initialize
    weight = 0.0;
    normal.set( 0.0, 0.0, 0.0 );

    // Loop through the triangles
    double tri_weight, A, B, C;
    GPoint p[3];
    GPoint* plist = g_mem.point_list();
    int* facet_list = g_mem.facet_list();
    int c = 0;
    for( ;c<g_mem.fListCount; )
    {
        p[0] = plist[facet_list[++c]];
        p[2] = plist[facet_list[++c]];
        p[1] = plist[facet_list[++c]]; 
        c++;

        // Get centroid
        CubitVector p1( p[0].x, p[0].y, p[0].z );
        CubitVector p2( p[2].x, p[2].y, p[2].z );
        CubitVector p3( p[1].x, p[1].y, p[1].z );

        CubitVector center = (p1 + p2 + p3)/3.0;

        CubitVector norm(ref_face->normal_at(center));

        // Get triangle area
        A = p1.y() * p2.z() + p1.z() * p3.y() + p2.y() * p3.z() -
            p2.z() * p3.y() - p1.y() * p3.z() - p1.z() * p2.y();

        B = p1.z() * p2.x() + p1.x() * p3.z() + p2.z() * p3.x() -
            p2.x() * p3.z() - p1.z() * p3.x() - p1.x() * p2.z();

        C = p1.x() * p2.y() + p1.y() * p3.x() + p2.x() * p3.y() -
            p2.y() * p3.x() - p1.x() * p3.y() - p1.y() * p2.x();

        //Note: triangle area = 0.5*(sqrt(A*A+B*B+C*C));

        tri_weight = 0.5*(A*A+B*B+C*C);

        normal += tri_weight * norm;

        weight += tri_weight;

    }

    normal.normalize();

    return CUBIT_SUCCESS;
}
void ProjectAll(HashParam& p, const Mat& feature, const Mat& proj, Mat& projectValue)
{	
	printf("start to project  ...\n");
	int nl = feature.rows;
	int nc = feature.cols;

	//hash every items
	//core:compute value for hash, but the type is continus, float, and not normalised
	projectValue.create(p.bucketNumber, nl, CV_32FC1);
	
	bool initMinMax = false;
	vector<float> p3(p.projectionSize, 0);
	
	for(int bucket = 0; bucket < p.bucketNumber; bucket ++)
	{
		for(int pp = 0; pp < nl; pp ++)
		{
			for(int tt = 0; tt < p.projectionSize; tt ++)
			{
				int cc = proj.at<int>(bucket, tt);
				p3[tt] = feature.at<float>(pp, cc);
			}
			//float k = getProjectValue(p, p3);
			float k = 0.0;
			float dtemp = 0.0;
			float variance = 0.0;
			vector<float> v1(p.projectionSize, 0), v2(p.projectionSize, 0);
			for(int tt = 0; tt < p.projectionSize; tt ++)
			{
				v1[tt] = p3[tt] - p.p1[tt];
				v2[tt] = p.p2[tt] - p.p1[tt];
				k += v1[tt] * v2[tt];
				dtemp += v2[tt] * v2[tt];
				variance += v1[tt] * v1[tt];
			}
			dtemp = sqrt(dtemp);
			k = k /dtemp;
			variance = sqrt(variance);
			float w = 1.0/variance;
			variance = acos(k/variance);
			//variance = w * variance;
			k = p.we * k + (1 - p.we) * variance;
			//k = (1 - w) * k + w * variance;
			projectValue.at<float>(bucket, pp) = k;
			//printf("%f ", k);
			
			if(initMinMax)
			{
				if(k > p.maxRange)
					p.maxRange = k;
				if(k < p.minRange)
					p.minRange = k;
			}
			else
			{
				p.maxRange = p.minRange = k;
				initMinMax = true;
			}
		}
		//printf("\n");
	}
	p.range = p.maxRange - p.minRange;
	printf("maxRange: %f, minRange: %f, range: %f.\n", p.maxRange, p.minRange, p.range);
}
int main(int argc, char* argv[])
{
	CS325Graphics window(argc, argv);

	float delta = 0.1;

	Point2D p1(CS325Graphics::X_MIN, CS325Graphics::Y_MAX / 4.5);
	Point2D p2(CS325Graphics::X_MAX, CS325Graphics::Y_MAX / 4.5);
	Point2D p3(CS325Graphics::X_MIN, CS325Graphics::Y_MIN);
	Point2D p4(CS325Graphics::X_MAX, CS325Graphics::Y_MAX);

	//Points 41, 42, 45, 46 control the sandbox. DON"T MESS WITH THEM!

	Point3D p30(0.5,  0.5,-3.5);
	Point3D p31(0.5, -0.5,-3.5);
	Point3D p32(-0.5,-0.5,-3.5);
	Point3D p33(-0.5, 0.5,-3.5);
	Point3D p34(0.5,  0.5,-1.5);
	Point3D p35(0.5, -0.5,-1.5);
	Point3D p36(-0.5,-0.5,-1.5);
	Point3D p37(-0.5, 0.5,-1.5);

	Point3D p40( -70.8, 28.8, -50.8);
	Point3D p41( 50.8,-2.8,  50.8);
	Point3D p42(-50.8,-2.8,  50.8);
	Point3D p43(-58.8, 25.8,  50.8);
	Point3D p44( 50.8, 50.8, -50.8);
	Point3D p45( 50.8,-2.8, -50.8);
	Point3D p46(-50.8,-2.8, -50.8);
	Point3D p47(-84.8,-2.8, -50.8);
	Point3D p49(-8.5,22.0, 50.8);
	Point3D p48(70,20,50.8);

	Point3D p50(3.5,  0.5,-3.5);
	Point3D p51(3.5, -0.5,-3.5);
	Point3D p52(2.5,-0.5,-3.5);
	Point3D p53(2.5, 0.5,-3.5);
	Point3D p54(3.5,  0.5,-1.5);
	Point3D p55(3.5, -0.5,-1.5);
	Point3D p56(2.5,-0.5,-1.5);
	Point3D p57(2.5, 0.5,-1.5);

	Point3D p60(3.5,  0.5, 13.5);
	Point3D p61(3.5, -0.5, 13.5);
	Point3D p62(2.5,-0.5,  13.5);
	Point3D p63(2.5, 0.5,  13.5);
	Point3D p64(3.5,  0.5, 16.5);
	Point3D p65(3.5, -0.5, 16.5);
	Point3D p66(2.5,-0.5,  16.5);
	Point3D p67(2.5, 0.5,  16.5);

	

	Point2D viewPos;
	Vector2D viewDir;
	Vector3D deltaV;
	viewDir.setAngle(0);


	// move view position

	for(int i = 0; i < MOVE_TEST; i){
		/*window.DrawLineOnScreen(p1, p2);*/
		//window.DrawLineOnScreen(p4, p3);

		window.DrawLineInSpace(p30, p31);
		window.DrawLineInSpace(p31, p32);
		window.DrawLineInSpace(p32, p33);
		window.DrawLineInSpace(p33, p30);
		window.DrawLineInSpace(p34, p35);
		window.DrawLineInSpace(p35, p36);
		window.DrawLineInSpace(p36, p37);
		window.DrawLineInSpace(p37, p34);
		window.DrawLineInSpace(p30, p34);
		window.DrawLineInSpace(p31, p35);
		window.DrawLineInSpace(p32, p36);
		window.DrawLineInSpace(p33, p37);

		window.DrawLineInSpace(p50, p51);
		window.DrawLineInSpace(p51, p52);
		window.DrawLineInSpace(p52, p53);
		window.DrawLineInSpace(p53, p50);
		window.DrawLineInSpace(p54, p55);
		window.DrawLineInSpace(p55, p56);
		window.DrawLineInSpace(p56, p57);
		window.DrawLineInSpace(p57, p54);
		window.DrawLineInSpace(p50, p54);
		window.DrawLineInSpace(p51, p55);
		window.DrawLineInSpace(p52, p56);
		window.DrawLineInSpace(p53, p57);

		window.DrawLineInSpace(p60, p61);
		window.DrawLineInSpace(p61, p62);
		window.DrawLineInSpace(p62, p63);
		window.DrawLineInSpace(p63, p60);
		window.DrawLineInSpace(p64, p65);
		window.DrawLineInSpace(p65, p66);
		window.DrawLineInSpace(p66, p67);
		window.DrawLineInSpace(p67, p64);
		window.DrawLineInSpace(p60, p64);
		window.DrawLineInSpace(p61, p65);
		window.DrawLineInSpace(p62, p66);
		window.DrawLineInSpace(p63, p67);


		//window.DrawLineInSpace(p40, p41);
		window.DrawLineInSpace(p41, p42);
		window.DrawLineInSpace(p42, p43);
		//window.DrawLineInSpace(p43, p40);
		//window.DrawLineInSpace(p44, p45);
		window.DrawLineInSpace(p45, p46);
		//window.DrawLineInSpace(p46, p47);
		//window.DrawLineInSpace(p47, p44);
		window.DrawLineInSpace(p40, p45);
		window.DrawLineInSpace(p41, p45);
		window.DrawLineInSpace(p42, p46);
		window.DrawLineInSpace(p43, p47);
		window.DrawLineInSpace(p40, p47);
		window.DrawLineInSpace(p41, p49);
		window.DrawLineInSpace(p42, p49);
		window.DrawLineInSpace(p41, p48);
		window.DrawLineInSpace(p45, p48);


				if(GetAsyncKeyState(VK_DOWN)) // the DOWN arrow was pressed, let's do something
		{
		delta = -.1;
		viewPos.setY(viewPos.getY() + cos(-viewDir.getAngle())*delta);
		viewPos.setX(viewPos.getX() + sin(-viewDir.getAngle())*delta);
		window.SetViewPosition(viewPos);
		cout << "view pos: " << viewPos.toString() << endl;

		window.DisplayNow();
		Sleep(50);
				}

			if(GetAsyncKeyState(VK_UP)) // the UP arrow was pressed, let's do something
		{
		delta = .1;
		viewPos.setY(viewPos.getY() + cos(-viewDir.getAngle())*delta);
		viewPos.setX(viewPos.getX() + sin(-viewDir.getAngle())*delta);
		window.SetViewPosition(viewPos);
		cout << "view pos: " << viewPos.toString() << endl;

		window.DisplayNow();
		Sleep(50);
				}
				if(GetAsyncKeyState(VK_RIGHT)) // the RIGHT arrow was pressed, let's do something
		{
	
		delta = .1;

		viewDir.setAngle(viewDir.getAngle()+delta);
		window.SetViewDirection(viewDir);
		cout << "view dir: " << viewDir.getAngle() << endl;

		window.DisplayNow();
		Sleep(50);	
			}
			
			if(GetAsyncKeyState(VK_LEFT)) // the LEFT arrow was pressed, let's do something
		{
	
		delta = -.1;

		viewDir.setAngle(viewDir.getAngle()+delta);
		window.SetViewDirection(viewDir);
		cout << "view dir: " << viewDir.getAngle() << endl;

		window.DisplayNow();
		Sleep(50);	
			}

		if(GetAsyncKeyState(VK_ESCAPE))
		{
			return 1;
		}
	}


		
	
}
Beispiel #11
0
static void split_convex(const std::vector<DPoint>& in,
                         std::vector<DPoint>& out, std::vector<size_t>& cvx)
{
    // initialization
    std::vector<DPoint>::const_iterator p=in.begin(), pmax = in.end();
    bool is_closed = (in.front()==in.back());

    if(in.size()<4) {
        while(p!=pmax)
            out.push_back(*p++);
        cvx.push_back( out.size() );
        return;
    }

    int ni = 0;
    DPoint p1(*p++),p2(*p++),p3(*p++);
    out.push_back(p1);
    int d2 = dir(p1.x, p1.y, p2.x, p2.y, p3.x, p3.y);

    // MAIN LOOP : d1=angle(P1-P2-P3) and d2=angle(P2-P3-P4)

    bool ok = true;
    std::vector<DPoint>::const_iterator first=in.begin();

    while (ok) {
        int d1 = d2;
        DPoint p4=*p++;
        d2 = dir(p2.x, p2.y, p3.x, p3.y, p4.x, p4.y);

        if(d1*d2>0) { // convex part: store point and increment p
            out.push_back(p1=p2);
            p2 = p3;
            p3 = p4;
        }
        else if(d1*d2<0) { // split curve
            out.push_back(p2);
            DPoint m = .5*(p2+p3);
            out.push_back(m);
            cvx.push_back( out.size() );
            if(p==first)
                ok=false;
            if(first==in.begin())
                first=p;
            if(ok) {
                if(is_closed && !ni) {
                    out.clear();
                    cvx.clear();
                    cvx.push_back(0);
                }
                out.push_back(m);
                ni++;
                p1 = p2;
                p2 = p3;
                p3 = p4;
            }
        } else { // undefined sign: remove one point
            if(d1==0 || d2==0) {
                if(d1==0)
                    p2 = p3;
                p3 = p4;
                d2 = dir(p1.x, p1.y, p2.x, p2.y, p3.x, p3.y);
            } else
                assert(false); // NaN in curve?
        }

        // test end of loop
        if(ok && p==pmax) {
            if (is_closed)
                p = in.begin()+1;
            else
                ok=false;
        }

        // stop for convex closed curves
        if(p==in.begin()+3 && ni==0)
            ok=false;
    }
    // END OF MAIN LOOP

    if (!is_closed) {
        out.push_back(p2);
        out.push_back(p3);
        cvx.push_back( out.size() );
    } else if(ni==0) { // convex closed curve */
        if (out.end() == out.begin()+1)
            out.push_back( out.front() );
        else
            out[0] = out.back();
        cvx.push_back( out.size() );
    }
}
Beispiel #12
0
void testController(){
	MemRepository* repo=new MemRepository();
	Controller c(repo);
	string errors="";
	Expense p(1, 21, 92, "clothing");
	c.add(p);
	assert(c.size()==1);
	Expense p1(2, 23, 440, "telephone");
	c.add(p1);
	assert(c.size()==2);
	Expense p2(3, 2, 9, "pizza");
	try{
		c.add(p2);
	}
	catch(RepositoryException& s)
	{
		errors+=s.getMsg();
	}
	assert(c.size()==2);
	assert(errors!="");

	errors="";
	Expense p3(3, 34, 29, "others");
	try{
		c.add(p2);
	}
	catch(RepositoryException& s)
	{
		errors+=s.getMsg();
	}
	assert(c.size()==2);
	assert(errors!="");

	Expense p4(1, 23, 440, "others");
	c.update(1,p4);
	vector<Expense*> all=c.getAll();
	assert(all.at(0)->getDay()==23);
	assert(c.size()==2);
	errors="";
	try{
		c.update(1,p3);
	}
	catch (RepositoryException& s1)
	{
		errors+=s1.getMsg();
	}
	assert(errors!="");

	c.remove(1);
	assert (c.size()==1);
	errors="";
	try{
		c.remove(7);
	}
	catch (RepositoryException& s1)
	{
		errors+=s1.getMsg();
	}
	assert(errors!="");
	assert (c.size()==1);

	c.add(p);
	all=c.filterByDay(23);
	assert(all.size()==1);
	all=c.filterByAmount(440);
	assert(all.size()==1);

	all=c.sortByAmountA();
	assert(all.at(0)->getId()==1);
	all=c.sortByAmountD();
	assert(all.at(0)->getId()==2);
	all=c.sortByTypeA();
	assert(all.at(0)->getId()==1);
	all=c.sortByTypeD();
	assert(all.at(0)->getId()==2);
}
Beispiel #13
0
void ImageViewer::displayMatches(QPainter& painter)const
{
	QPoint pt1, pt2;

	if (siftObj1.keypoints==NULL){
		printf("ERROR : Keypoints NULL\n");
		exit(-1);
	}
		
	if (dispMatch && lastComparison.tab_match!=NULL && !siftObj1.IsEmpty() ){
		// Display matches
		for (int i=0;i<lastComparison.nb_match;i++) {
			pt1.setX(ROUND(lastComparison.tab_match[i].x1));
			pt1.setY(ROUND(lastComparison.tab_match[i].y1));
			pt2.setX(ROUND(lastComparison.tab_match[i].x2));
			pt2.setY(ROUND(lastComparison.tab_match[i].y2 + siftObj1.im->height));
			
			painter.setBrush(Qt::white);
			if (lastComparison.tab_match[i].id==0)
				painter.setPen(Qt::red); //red for discarded matches
			else painter.setPen(Qt::green); //green
			
			painter.drawLine(pt1, pt2);
			painter.drawEllipse(pt1, 3, 3);
			painter.drawEllipse(pt2, 3, 3);
		}
	}
	
	#ifdef AAA
		
	//IplImage * im,* imcol;
	QSize s;
	//QPoint pt1, pt2;
	//CvScalar color;
	int i,j,im2null=0;
	Keypoint k1*=siftObj1->keypoints;
	Keypoint k2*=siftObj2->keypoints;
		/*Affine transform of the image border*/
		
		if (param.size_m()>0) {
			Matrice p1(2,1), p2(2,1), p3(2,1), p4(2,1), transl(2,1);
			transl.set_val(0,0,0);
			transl.set_val(1,0,im1->height);
			p1.set_val(0,0,0);
			p1.set_val(1,0,0);
			p2.set_val(0,0,im1->width);
			p2.set_val(1,0,0);
			p3.set_val(0,0,im1->width);
			p3.set_val(1,0,im1->height);
			p4.set_val(0,0,0);
			p4.set_val(1,0,im1->height);
			
			p1=Transform(p1,param)+transl;
			p2=Transform(p2,param)+transl;
			p3=Transform(p3,param)+transl;
			p4=Transform(p4,param)+transl;
			
			color=CV_RGB(0,128,255); //light blue
			pt1.x=ROUND(p1.get_val(0,0));
			pt1.y=ROUND(p1.get_val(1,0));
			pt2.x=ROUND(p2.get_val(0,0));
			pt2.y=ROUND(p2.get_val(1,0));
			cvLine(imcol, pt1, pt2, color, 1);
			pt1.x=ROUND(p2.get_val(0,0));
			pt1.y=ROUND(p2.get_val(1,0));
			pt2.x=ROUND(p3.get_val(0,0));
			pt2.y=ROUND(p3.get_val(1,0));
			cvLine(imcol, pt1, pt2, color, 1);
			pt1.x=ROUND(p3.get_val(0,0));
			pt1.y=ROUND(p3.get_val(1,0));
			pt2.x=ROUND(p4.get_val(0,0));
			pt2.y=ROUND(p4.get_val(1,0));
			cvLine(imcol, pt1, pt2, color, 1);
			pt1.x=ROUND(p4.get_val(0,0));
			pt1.y=ROUND(p4.get_val(1,0));
			pt2.x=ROUND(p1.get_val(0,0));
			pt2.y=ROUND(p1.get_val(1,0));
			cvLine(imcol, pt1, pt2, color, 1);
			
			/* Draw the border of the object */
			CvMemStorage *storage= cvCreateMemStorage (0); /* Memory used by openCV */
			int header_size = sizeof( CvContour );
			CvSeq *contours;
			
			IplImage* imthres = cvCreateImage(cvSize(im1->width,im1->height),IPL_DEPTH_8U, 1 );
			cvCopy( im1, imthres, 0 );
			
			/* First find the contour of a thresholded image*/
			
			cvThreshold(imthres, imthres, border_threshold, 255, CV_THRESH_BINARY );
			cvFindContours ( imthres, storage, &contours, header_size, CV_RETR_LIST, CV_CHAIN_APPROX_SIMPLE);
			
			/* For each contour found*/
			
			while ( contours != NULL) {
				double area=fabs(cvContourArea(contours,CV_WHOLE_SEQ)); // compute area
				if ( area > 20) {
					for (int i=0;i<contours->total;i++) {
						
						/* Compute transform of contour*/
						
						CvPoint* cvpt=(CvPoint*)cvGetSeqElem( contours, i);
						p1.set_val(0,0,cvpt->x);
						p1.set_val(1,0,cvpt->y);
						p1= Transform(p1,param) + transl;
						cvpt->x=ROUND(p1.get_val(0,0));
						cvpt->y=ROUND(p1.get_val(1,0));
					}
					//                cvDrawContours( imcol, contours, CV_RGB(0,0,255),CV_RGB(255,0,0),0,2,8);
					cvDrawContours( imcol, contours, CV_RGB(0,0,255),CV_RGB(0,0,255),0,2,8);
				}
				contours = contours->h_next; // ?????
			}
			free( contours );
			cvReleaseMemStorage( &storage );
			
	}
	#endif
}
void ShapeFunctionTriangleSigned::calc()
{
    // based on the answer in http://answers.unity3d.com/questions/383804/calculate-uv-coordinates-of-3d-point-on-plane-of-m.html
    // check out also: http://www.had2know.com/academics/triangle-area-perimeter-angle-3-coordinates.html
    lmx::Vector<double> f(dim), p1(dim), p2(dim), p3(dim);
    f.writeElement(gp->getX(),0);
    f.writeElement(gp->getY(),1);
    f.writeElement(gp->getZ(),2);
    p1.writeElement(gp->getSupportNodes()[0]->getX(), 0);
    p1.writeElement(gp->getSupportNodes()[0]->getY(), 1);
    p1.writeElement(gp->getSupportNodes()[0]->getZ(), 2);
    p2.writeElement(gp->getSupportNodes()[1]->getX(), 0);
    p1.writeElement(gp->getSupportNodes()[1]->getY(), 1);
    p1.writeElement(gp->getSupportNodes()[1]->getZ(), 2);
    p3.writeElement(gp->getSupportNodes()[2]->getX(), 0);
    p1.writeElement(gp->getSupportNodes()[2]->getY(), 1);
    p1.writeElement(gp->getSupportNodes()[2]->getZ(), 2);

    lmx::Vector<double> f1(dim), f2(dim), f3(dim); // calculate vectors from point f to vertices p1, p2 and p3:
    f1.subs( p1, f);
    f2.subs( p2, f);
    f3.subs( p3, f);
    lmx::Vector<double> va(dim), va1(dim), va2(dim), va3(dim);
    double a, a1, a2, a3;
    va.multElements(p1-p2, p1-p3);
    va1.multElements(f2, f3);
    va2.multElements(f3, f1);
    va3.multElements(f1, f2);
    lmx::Vector<double> vaa1(dim), vaa2(dim), vaa3(dim);
    a = va.norm2();
    a1 = std::copysign( va1.norm2()/a, va*va1 );
    a2 = std::copysign( va2.norm2()/a, va*va2 );
    a3 = std::copysign( va3.norm2()/a, va*va3 );

    phi.writeElement( a1, 0, 0 );
    phi.writeElement( a2, 0, 0 );
    phi.writeElement( a3, 0, 0 );
    //////////////////////////////////////////////////////////////////
    // FIRST DERIVATIVES:
    //////////////////////////////////////////////////////////////////
//   phi.writeElement(
//       ( gp->supportNodes[1]->gety() - gp->supportNodes[2]->gety() )
//       / ( 2*gp->jacobian ), 1, 0 );
//   phi.writeElement(
//       ( gp->supportNodes[2]->getx() - gp->supportNodes[1]->getx() )
//       / ( 2*gp->jacobian ), 2, 0 );
//   //////////////////////////////////////////////////////////////////
//   phi.writeElement(
//       ( gp->supportNodes[2]->gety() - gp->supportNodes[0]->gety() )
//       / ( 2*gp->jacobian ), 1, 1 );
//   phi.writeElement(
//       ( gp->supportNodes[0]->getx() - gp->supportNodes[2]->getx() )
//       / ( 2*gp->jacobian ), 2, 1 );
//   //////////////////////////////////////////////////////////////////
//   phi.writeElement(
//       ( gp->supportNodes[0]->gety() - gp->supportNodes[1]->gety() )
//       / ( 2*gp->jacobian ), 1, 2 );
//   phi.writeElement(
//       ( gp->supportNodes[1]->getx() - gp->supportNodes[0]->getx() )
//       / ( 2*gp->jacobian ), 2, 2 );

//   cout << "phi = " << phi << endl;
}
Beispiel #15
0
int main(int argc , char* argv[]){
		
		//Program Options

	po::options_description desc("Allowed Options");
	desc.add_options()
		 ("help,h", "Produce this help message")
		 ("startwl,s",po::value<double>(),"Set the start Wavelength for the Analysis")
		 ("stopwl,p",po::value<double>(),"Set the stop Wavelength for the Analysis")
		 ("non-interactive,n","Runs the program in Noninteractive mode. It quits when it's finished")
		 ("version,v","Prints Version")
	;
		 
	po::variables_map vm;
		 po::store(po::parse_command_line(argc,argv,desc),vm);
		 po::notify(vm);
	if (vm.count("help")) {
		std::cout << desc<< std::endl;
		return 3;
	}
	if (vm.count("version")) {
		std::cout << "VCSEL Laser Analysis Version " << _VERSION << std::endl;
		std::cout << "Using ROOT version " << _ROOT_VERSION << " and Boost version " << _BOOST_VERSION << std::endl;
		return 0;
	}
	
	if (argc < 4) {
		std::cout << desc;
		return 2;
	}	
	double startwl, stopwl;
	startwl = 842.;
	stopwl = 860.;
	bool run = true;
	if (vm.count("startwl")) {
		startwl = vm["startwl"].as<double>();
		NUM_ARGS +=2;
	}
	if (vm.count("stopwl")) {
		double tmp =  vm["stopwl"].as<double>();
		stopwl =tmp;
		NUM_ARGS +=2;
	}
	if (vm.count("non-interactive")) {
		run = false;
		NUM_ARGS++;
	}
	
	
	//checking filetypes must be txt, csv or CSV
	if (!check_extensions(argc, argv)) {
		return 1;
	}
	std::cout <<"startwl: "<< startwl << '\t' << "stopwl: " << stopwl << std::endl;
	
	Double_t max = -210;
	Double_t maxwl = 0;
	int _argc = argc;
	TApplication *t = new TApplication("big",&_argc,argv);
	std::cout << "Running with boost and ROOT" <<std::endl;
	std::vector<double> _x,_y;
	Double_t x[LINES], y[LINES], _inta[LINES], _intb[LINES]; 
	
	Double_t *cmp_int = new Double_t[argc];
	Double_t *argc_ary = new Double_t[argc];
	Double_t *cmp_int_root = new Double_t[argc];
	Double_t *asymmety_ary = new Double_t[argc];
	Double_t *width_ary = new Double_t [argc];
	

	
	TGraph2D *gr = new TGraph2D(LINES*(argc-1));
		//Setting up canvas for plot of all sectrums (is it called spectrums? ;) )
	TCanvas *c1 = new TCanvas("All Plots","All Plots",10,10,3000,1500);
	TH1F *integral_hist = new TH1F("Asymmerty", "Asymmetry", 100,0, 100);
	

	if(!(argc % ROWS)){
		c1->Divide(argc/ROWS,ROWS);
		
	}else{
		c1->Divide(argc/ROWS+(argc %ROWS -1),ROWS);
	}
	
	for (Int_t i = NUM_ARGS +1; i < argc ; i++){
		try{ 
			
			max = -211;
			maxwl = 0;
			argc_ary[i] = i-NUM_ARGS;
			
			std::ifstream in;
			in.seekg(0, std::ios::beg);
				// voodoo keep this;
			char **arg1 = t->Argv() ;
			std::string tmp = arg1[i];
			in.open(tmp.c_str());
			
			std::cout<< "file: " << tmp << std::endl;
			std::string line;
			int cline = 0;
			std::vector<double> a,b, inta, intb;
			
				//reading file
			
			while(getline(in,line)){
				read_file(line, a, b, inta, intb);
				cline++;
			}
			
			if (cline < LINES){
				for(int i = cline ; i < LINES ; i++){
					a.push_back(100);
					b.push_back(-70);
				}
			}
			std::cout<< "\n\ncline: " << cline<< std::endl; 
			cline =(cline > LINES) ? LINES :cline;
			
			for(Int_t j = 0; j <LINES ;j++){
				x[j] = a[j];
				y[j] = b[j];
				_inta[j] = inta[j];
				_intb[j]= (intb[j] < 0)? 0:intb[j];
			}
			
			
			
			double s_integral = 0;
			
			std::cout <<"size of int " <<  intb.size()<< std::endl;
			for (size_t it = 0; it < intb.size() - 1; it++){
				double y_val = (intb[it]+intb[it+1])/2;
				assert (y_val >= 0);
				double area = 0.002*y_val;
				if(area > 0 )
					s_integral += area;
			}
			
			
			
			
			std::cout << "Simpson integral: " <<s_integral <<std::endl;
			integral_hist->Fill(s_integral);
			cmp_int[i] = s_integral;
			Int_t lines = (Int_t)intb.size();
			TGraph *r_integral = new TGraph(lines, _inta, _intb);
			
			std::cout << "ROOT integral: " << r_integral->Integral() << std::endl;
			cmp_int_root[i] = r_integral->Integral();
			
				//expanding
				//expand(y, THRS_EXPAND, RATIO_EXPAND, LINES);
			
			
				//Filling TGraph2D
			
			for(Int_t j = 0; j <LINES ; j++){
				if (y[j] > max){
					max = y[j];
					maxwl = x[j];
				}
				gr->SetPoint(j+i*LINES, x[j],i,y[j]);
			}
			
			
			in.seekg(0, std::ios::beg);
			in.close();
			
				//Plotting each spectrum
			
			TGraph *_gr = new TGraph(LINES,x,y);
			_gr->GetHistogram()->GetXaxis()->SetTitle("#lambda in nm");
			_gr->GetHistogram()->GetYaxis()->SetTitle("Intensity in dB");
			c1->cd(i-NUM_ARGS);
			_gr->Draw("AP");
			_gr->GetYaxis()->SetRangeUser(-80.,-10.);
			_gr->GetXaxis()->SetRangeUser(startwl,stopwl);
			_gr->SetTitle(tmp.c_str());
			c1->Update();
			
			
				//Calculating asymmetry
			std::cout << "maximum: " << max << std::endl;
			double leftlimit, rightlimit = 1;
			leftlimit = findlower(x,y, max);
			rightlimit = findupper(x,y, max);
			if (leftlimit != 1 && rightlimit != 1){
				width_ary[i] = (leftlimit +rightlimit)/2;
			}else{
				width_ary[i] = maxwl;
			}
			double calced_asy = (maxwl-leftlimit)/(rightlimit-maxwl);
			asymmety_ary[i-NUM_ARGS] = calced_asy;
			
			std::cout << "Asymmetry: " << calced_asy << std::endl;
			
		}catch(std::exception e){
			std::cout << e.what()<< std::endl;
		}
	}
	
	
		//Setting style for 3D Plot
	TCanvas *d = new TCanvas("big","big",10,10,1500,800);
	d->Divide(2,2);
	d->cd(1);
	TGraph *the_ints = new TGraph(argc-1,argc_ary,cmp_int);
	the_ints->Draw("A*");
	the_ints->SetTitle("My Ints");
	d->Update();
	d->cd(2);
	std::cout << "Fitting\n\n";
	integral_hist->SetFillColor(kBlue);
		//settig everything to print fitresuts
	gStyle->SetOptStat(1211);
	gStyle->SetOptFit(1111);
	integral_hist->Draw();
	integral_hist->Fit("gaus","W","" ,10,100);
		//integral_hist->Draw("SAME");
	d->Update();
	d->cd(3);
	
	TGraph *roots_int = new TGraph(argc-1, argc_ary, cmp_int_root);
	roots_int->SetTitle("ROOTS Int");
	roots_int->Draw("A*");
	d->Update();
	d->cd(4);
	d->Update();
		//gROOT->SetStyle("modern");
	gr->SetTitle("big");
	gr->GetHistogram("empty")->GetXaxis()->SetTitle("#lambda in nm");
	gr->GetHistogram("empty")->GetXaxis()->SetLimits(startwl,stopwl);
	gr->GetHistogram("empty")->GetYaxis()->SetTitle("Messurement"); 
	gr->GetHistogram("empty")->GetZaxis()->SetTitle("Intensity in dB");
	gr->GetHistogram("empty")->GetXaxis()->SetTitleOffset(1.5);
	gr->GetHistogram("empty")->GetYaxis()->SetTitleOffset(1.5);
	gr->GetHistogram("empty")->GetZaxis()->SetTitleOffset(1.5);
	gr->GetHistogram("empty")->GetZaxis()->SetRangeUser(-70.,max);
	gr->GetHistogram("empty")->GetXaxis()->CenterTitle();
	gr->GetHistogram("empty")->GetYaxis()->CenterTitle();
	gr->GetHistogram("empty")->GetZaxis()->CenterTitle();
	gr->Draw("PCOL");
	d->SetFillColor(16);
	
	
#ifdef RENDER
		//Render 3D animation
	const Int_t kUPDATE = 1;
	TSlider *slider = 0;
	
	for (Int_t i = 1; i <= 125; i++){
		TView3D *v = new TView3D();
		v->RotateView(5+i,45+i,d);
			//d->Update();
		
		if(i && (i%kUPDATE)== 0){
			if (i == kUPDATE){
				gr->Draw("PCOL");
				d->Update();
				slider = new TSlider("slider","test",850,-70,856,max);
			}
			if (slider) slider->SetRange(0,Float_t(i)/10000.);
			d->Modified();
			d->Update();
			d->Print("3d.gif+");
		} 
	}
	d->Update();
	d->Print("3d.gif++");
#endif
	
	
		//Saving image
	TImage *img = TImage::Create();
	boost::filesystem::path p(t->Argv(3));
	std::string file = p.parent_path().string();
	file += "_big.png";
	img->FromPad(d);
	img->WriteImage(file.c_str());
		//cleaning
	
	TCanvas *e = new TCanvas("Asymmetry","Asymmetry",10,10,1500,800);
	e->Divide(2,1);
	TGraph *asy_plot = new TGraph(argc-1, argc_ary, asymmety_ary);
	e->cd(1);
	asy_plot->SetTitle("Asymmetry");
	asy_plot->GetHistogram()->GetXaxis()->SetTitle("# Meassurement");
	asy_plot->GetHistogram()->GetYaxis()->SetTitle("Asymmetry");
	asy_plot->GetHistogram()->GetXaxis()->SetRange(1, argc);
	asy_plot->Draw("A*");
	e->Update();
	e->cd(2);
	
	
	TGraph *center_plot = new TGraph(argc-1 , argc_ary, width_ary);
	center_plot->GetHistogram()->GetXaxis()->SetTitle("# Meassurement");
	center_plot->GetHistogram()->GetYaxis()->SetTitle("Center in nm");
	center_plot->GetHistogram()->GetYaxis()->SetRangeUser(startwl, stopwl);
	center_plot->SetTitle("Center");
	center_plot->Draw("A*");
	e->Update();
		//Saving Images
	TImage *secimg = TImage::Create();
	boost::filesystem::path p2(t->Argv(3));
	file = p2.parent_path().string();
	file += "_asy_cent.png";
	secimg->FromPad(e);
	secimg->WriteImage(file.c_str());
	
	TImage *thrdimg = TImage::Create();
	boost::filesystem::path p3(t->Argv(3));
	file = p3.parent_path().string();
	file += "_allplots.png";
	thrdimg->FromPad(c1);
	thrdimg->WriteImage(file.c_str());
	
		//detecting Gradients
	gradient(asymmety_ary, width_ary,cmp_int, argc-1,c1);
	std::cout << "\n\n\nDone !!\nYou can quit now using CTRL+C \n" ;
	
	if (run == true){
		t->Run();
	}
	std::cout << "With \n" ;
	
	delete[] cmp_int;
	delete[] argc_ary; 
	delete[] cmp_int_root;
	delete[] asymmety_ary;
	delete[] width_ary;
	return 0;
}
Beispiel #16
0
void Slur::computeBezier(SlurSegment* ss, QPointF p6o)
      {
      qreal _spatium  = spatium();
      qreal shoulderW;              // height as fraction of slur-length
      qreal shoulderH;
      //
      // p1 and p2 are the end points of the slur
      //
      QPointF pp1 = ss->ups[GRIP_START].p + ss->ups[GRIP_START].off * _spatium;
      QPointF pp2 = ss->ups[GRIP_END].p   + ss->ups[GRIP_END].off   * _spatium;

      QPointF p2 = pp2 - pp1;
      if ((p2.x() == 0.0) && (p2.y() == 0.0)) {
            qDebug("zero slur");
abort();
            Measure* m1 = startChord()->segment()->measure();
            Measure* m2 = endChord()->segment()->measure();
            Page* page = m1->system()->page();
            qDebug("   at tick %d in measure %d-%d page %d",
               m1->tick(), m1->no(), m2->no(), page->no());
            return;
            }

      qreal sinb = atan(p2.y() / p2.x());
      QTransform t;
      t.rotateRadians(-sinb);
      p2  = t.map(p2);
      p6o = t.map(p6o);

      double smallH = 0.5;
      qreal d = p2.x() / _spatium;
      if (d <= 2.0) {
            shoulderH = d * 0.5 * smallH * _spatium;
            shoulderW = .6;
            }
      else {
            qreal dd = log10(1.0 + (d - 2.0) * .5) * 2.0;
            if (dd > 3.0)
                  dd = 3.0;
            shoulderH = (dd + smallH) * _spatium;
            if (d > 18.0)
                  shoulderW = 0.7; // 0.8;
            else if (d > 10)
                  shoulderW = 0.6; // 0.7;
            else
                  shoulderW = 0.5; // 0.6;
            }

      shoulderH -= p6o.y();

      if (!up())
            shoulderH = -shoulderH;

      qreal c    = p2.x();
      qreal c1   = (c - c * shoulderW) * .5 + p6o.x();
      qreal c2   = c1 + c * shoulderW       + p6o.x();

      QPointF p5 = QPointF(c * .5, 0.0);

      QPointF p3(c1, -shoulderH);
      QPointF p4(c2, -shoulderH);

      qreal w = (score()->styleS(ST_SlurMidWidth).val() - score()->styleS(ST_SlurEndWidth).val()) * _spatium;
      if (((c2 - c1) / _spatium) <= _spatium)
            w *= .5;
      QPointF th(0.0, w);    // thickness of slur

      QPointF p3o = p6o + t.map(ss->ups[GRIP_BEZIER1].off * _spatium);
      QPointF p4o = p6o + t.map(ss->ups[GRIP_BEZIER2].off * _spatium);

      if(!p6o.isNull()) {
            QPointF p6i = t.inverted().map(p6o) / _spatium;
            ss->ups[GRIP_BEZIER1].off += p6i ;
            ss->ups[GRIP_BEZIER2].off += p6i;
            }

      //-----------------------------------calculate p6
      QPointF pp3  = p3 + p3o;
      QPointF pp4  = p4 + p4o;
      QPointF ppp4 = pp4 - pp3;

      qreal r2 = atan(ppp4.y() / ppp4.x());
      t.reset();
      t.rotateRadians(-r2);
      QPointF p6  = QPointF(t.map(ppp4).x() * .5, 0.0);

      t.rotateRadians(2 * r2);
      p6 = t.map(p6) + pp3 - p6o;
      //-----------------------------------

      ss->path = QPainterPath();
      ss->path.moveTo(QPointF());
      ss->path.cubicTo(p3 + p3o - th, p4 + p4o - th, p2);
      if (lineType() == 0)
            ss->path.cubicTo(p4 +p4o + th, p3 + p3o + th, QPointF());

      th = QPointF(0.0, 3.0 * w);
      ss->shapePath = QPainterPath();
      ss->shapePath.moveTo(QPointF());
      ss->shapePath.cubicTo(p3 + p3o - th, p4 + p4o - th, p2);
      ss->shapePath.cubicTo(p4 +p4o + th, p3 + p3o + th, QPointF());

      // translate back
      t.reset();
      t.translate(pp1.x(), pp1.y());
      t.rotateRadians(sinb);
      ss->path                 = t.map(ss->path);
      ss->shapePath            = t.map(ss->shapePath);
      ss->ups[GRIP_BEZIER1].p  = t.map(p3);
      ss->ups[GRIP_BEZIER2].p  = t.map(p4);
      ss->ups[GRIP_END].p      = t.map(p2) - ss->ups[GRIP_END].off * _spatium;
      ss->ups[GRIP_DRAG].p     = t.map(p5);
      ss->ups[GRIP_SHOULDER].p = t.map(p6);
      }
Beispiel #17
0
void BlockType::drawBlock(TriangleCollector *collector, const Block &block) const
{
	collector->setCurrentBlock(block);
	int type = block.getType();
	if (blockTypeSpec[type].type == Type_Cube)
	{
		const Tile &tile = blockTypeSpec[type].tile;
		/*        |y
		 *        |
		 *        1----------2
		 *       /|         /|
		 *      / |        / |
		 *     /  |       /  |
		 *    3---+------4   |
		 *    |   5------+---6------x
		 *    |  /       |  /
		 *    | /        | /
		 *    |/         |/
		 *    7----------8
		 *   /
		 *  /z
		 */
		float3 p1(0, 1, 0);
		float3 p2(1, 1, 0);
		float3 p3(0, 1, 1);
		float3 p4(1, 1, 1);

		float3 p5(0, 0, 0);
		float3 p6(1, 0, 0);
		float3 p7(0, 0, 1);
		float3 p8(1, 0, 1);

		Block b[3][3][3];
		for (int x = -1; x <= 1; x++)
			for (int y = -1; y <= 1; y++)
				for (int z = -1; z <= 1; z++)
					b[x + 1][y + 1][z + 1] = block.getNeighbour(x, y, z);

		drawFace(collector, tile, p4, p2, p8, p6,
			b[2][2][2], b[2][2][1], b[2][2][0],
			b[2][1][2], b[2][1][1], b[2][1][0],
			b[2][0][2], b[2][0][1], b[2][0][0],
			float3(1, 0, 0));

		drawFace(collector, tile, p1, p3, p5, p7,
			b[0][2][0], b[0][2][1], b[0][2][2],
			b[0][1][0], b[0][1][1], b[0][1][2],
			b[0][0][0], b[0][0][1], b[0][0][2],
			float3(-1, 0, 0));

		drawFace(collector, tile, p1, p2, p3, p4,
			b[0][2][0], b[1][2][0], b[2][2][0],
			b[0][2][1], b[1][2][1], b[2][2][1],
			b[0][2][2], b[1][2][2], b[2][2][2],
			float3(0, 1, 0));

		drawFace(collector, tile, p7, p8, p5, p6,
			b[0][0][2], b[1][0][2], b[2][0][2],
			b[0][0][1], b[1][0][1], b[2][0][1],
			b[0][0][0], b[1][0][0], b[2][0][0],
			float3(0, -1, 0));

		drawFace(collector, tile, p3, p4, p7, p8,
			b[0][2][2], b[1][2][2], b[2][2][2],
			b[0][1][2], b[1][1][2], b[2][1][2],
			b[0][0][2], b[1][0][2], b[2][0][2],
			float3(0, 0, 1));

		drawFace(collector, tile, p2, p1, p6, p5,
			b[2][2][0], b[1][2][0], b[0][2][0],
			b[2][1][0], b[1][1][0], b[0][1][0],
			b[2][0][0], b[1][0][0], b[0][0][0],
			float3(0, 0, -1));
	}
}
Beispiel #18
0
void main()
{
	LinkedList list;
	Point p1(17.0f,12.5f);
	Point p2(1.0f,99.0f);
	Point p3(38.0f,1.2f);

	list.GetItem();

	/*list.Add(p1);
	list.Add(p2);
	list.Add(p3);

	list.Head();

	std::cout << list.GetItem().X() << std::endl;
	std::cout << list.GetItem().Y() << std::endl << std::endl;

	list.Next();

	std::cout << list.GetItem().X() << std::endl;
	std::cout << list.GetItem().Y() << std::endl << std::endl;

	list.Prev();

	std::cout << list.GetItem().X() << std::endl;
	std::cout << list.GetItem().Y() << std::endl << std::endl;

	list.Tail();

	std::cout << list.GetItem().X() << std::endl;
	std::cout << list.GetItem().Y() << std::endl << std::endl;

	LinkedList list2;

	list2.Add(Point(99,55));
	list2.Add(Point(88,55));
	list2.Add(Point(77,55));
	list2.Add(Point(66,55));

	list2.Head();

	std::cout << list2.GetItem().X() << std::endl;
	std::cout << list2.GetItem().Y() << std::endl << std::endl;

	list2.Next();

	std::cout << list2.GetItem().X() << std::endl;
	std::cout << list2.GetItem().Y() << std::endl << std::endl;

	list2.Tail();

	std::cout << list2.GetItem().X() << std::endl;
	std::cout << list2.GetItem().Y() << std::endl << std::endl;

	list2.Prev();

	std::cout << list2.GetItem().X() << std::endl;
	std::cout << list2.GetItem().Y() << std::endl << std::endl;

	list2.Remove();

	std::cout << list2.GetItem().X() << std::endl;
	std::cout << list2.GetItem().Y() << std::endl << std::endl;

	list2.Remove();

	std::cout << list2.GetItem().X() << std::endl;
	std::cout << list2.GetItem().Y() << std::endl << std::endl;

	list2.Head();

	std::cout << list2.GetItem().X() << std::endl;
	std::cout << list2.GetItem().Y() << std::endl << std::endl;

	list2.Remove();

	std::cout << list2.GetItem().X() << std::endl;
	std::cout << list2.GetItem().Y() << std::endl << std::endl;

	StackFIFO StackF;

	StackF.Add(Point(99,11));
	StackF.Add(Point(88,11));
	StackF.Add(Point(77,11));
	StackF.Add(Point(66,11));
	StackF.Add(Point(55,11));

	Point p1 = StackF.Get();
	Point p2 = StackF.Get();

	StackLIFO StackL;

	StackL.Add(Point(99,11));
	StackL.Add(Point(88,11));
	StackL.Add(Point(77,11));
	StackL.Add(Point(66,11));
	StackL.Add(Point(55,11));

	Point p1 = StackL.Pop();
	Point p2 = StackL.Pick();*/

}
Beispiel #19
0
/*
 * Dump TCP statistics structure.
 */
void
tcp_stats(u_long off, char *name)
{
	struct tcpstat tcpstat;

	if (off == 0)
		return;
	printf("%s:\n", name);
	kread(off, (char *)&tcpstat, sizeof (tcpstat));

#define	p(f, m) if (tcpstat.f || sflag <= 1) \
	printf(m, tcpstat.f, plural(tcpstat.f))
#define	p1(f, m) if (tcpstat.f || sflag <= 1) \
	printf(m, tcpstat.f)
#define	p2(f1, f2, m) if (tcpstat.f1 || tcpstat.f2 || sflag <= 1) \
	printf(m, tcpstat.f1, plural(tcpstat.f1), tcpstat.f2, plural(tcpstat.f2))
#define	p2a(f1, f2, m) if (tcpstat.f1 || tcpstat.f2 || sflag <= 1) \
	printf(m, tcpstat.f1, plural(tcpstat.f1), tcpstat.f2)
#define	p3(f, m) if (tcpstat.f || sflag <= 1) \
	printf(m, tcpstat.f, plurales(tcpstat.f))

	p(tcps_sndtotal, "\t%u packet%s sent\n");
	p2(tcps_sndpack,tcps_sndbyte,
	    "\t\t%u data packet%s (%qd byte%s)\n");
	p2(tcps_sndrexmitpack, tcps_sndrexmitbyte,
	    "\t\t%u data packet%s (%qd byte%s) retransmitted\n");
	p(tcps_sndrexmitfast, "\t\t%qd fast retransmitted packet%s\n");
	p2a(tcps_sndacks, tcps_delack,
	    "\t\t%u ack-only packet%s (%u delayed)\n");
	p(tcps_sndurg, "\t\t%u URG only packet%s\n");
	p(tcps_sndprobe, "\t\t%u window probe packet%s\n");
	p(tcps_sndwinup, "\t\t%u window update packet%s\n");
	p(tcps_sndctrl, "\t\t%u control packet%s\n");
	p(tcps_outhwcsum, "\t\t%u packet%s hardware-checksummed\n");
	p(tcps_rcvtotal, "\t%u packet%s received\n");
	p2(tcps_rcvackpack, tcps_rcvackbyte, "\t\t%u ack%s (for %qd byte%s)\n");
	p(tcps_rcvdupack, "\t\t%u duplicate ack%s\n");
	p(tcps_rcvacktoomuch, "\t\t%u ack%s for unsent data\n");
	p2(tcps_rcvpack, tcps_rcvbyte,
	    "\t\t%u packet%s (%qu byte%s) received in-sequence\n");
	p2(tcps_rcvduppack, tcps_rcvdupbyte,
	    "\t\t%u completely duplicate packet%s (%qd byte%s)\n");
	p(tcps_pawsdrop, "\t\t%u old duplicate packet%s\n");
	p2(tcps_rcvpartduppack, tcps_rcvpartdupbyte,
	    "\t\t%u packet%s with some duplicate data (%qd byte%s duplicated)\n");
	p2(tcps_rcvoopack, tcps_rcvoobyte,
	    "\t\t%u out-of-order packet%s (%qd byte%s)\n");
	p2(tcps_rcvpackafterwin, tcps_rcvbyteafterwin,
	    "\t\t%u packet%s (%qd byte%s) of data after window\n");
	p(tcps_rcvwinprobe, "\t\t%u window probe%s\n");
	p(tcps_rcvwinupd, "\t\t%u window update packet%s\n");
	p(tcps_rcvafterclose, "\t\t%u packet%s received after close\n");
	p(tcps_rcvbadsum, "\t\t%u discarded for bad checksum%s\n");
	p(tcps_rcvbadoff, "\t\t%u discarded for bad header offset field%s\n");
	p1(tcps_rcvshort, "\t\t%u discarded because packet too short\n");
	p1(tcps_rcvnosec, "\t\t%u discarded for missing IPsec protection\n");
	p1(tcps_rcvmemdrop, "\t\t%u discarded due to memory shortage\n");
	p(tcps_inhwcsum, "\t\t%u packet%s hardware-checksummed\n");
	p(tcps_rcvbadsig, "\t\t%u bad/missing md5 checksum%s\n");
	p(tcps_rcvgoodsig, "\t\t%qd good md5 checksum%s\n");
	p(tcps_connattempt, "\t%u connection request%s\n");
	p(tcps_accepts, "\t%u connection accept%s\n");
	p(tcps_connects, "\t%u connection%s established (including accepts)\n");
	p2(tcps_closed, tcps_drops,
	    "\t%u connection%s closed (including %u drop%s)\n");
	p(tcps_conndrained, "\t%qd connection%s drained\n");
	p(tcps_conndrops, "\t%u embryonic connection%s dropped\n");
	p2(tcps_rttupdated, tcps_segstimed,
	    "\t%u segment%s updated rtt (of %u attempt%s)\n");
	p(tcps_rexmttimeo, "\t%u retransmit timeout%s\n");
	p(tcps_timeoutdrop, "\t\t%u connection%s dropped by rexmit timeout\n");
	p(tcps_persisttimeo, "\t%u persist timeout%s\n");
	p(tcps_keeptimeo, "\t%u keepalive timeout%s\n");
	p(tcps_keepprobe, "\t\t%u keepalive probe%s sent\n");
	p(tcps_keepdrops, "\t\t%u connection%s dropped by keepalive\n");
	p(tcps_predack, "\t%u correct ACK header prediction%s\n");
	p(tcps_preddat, "\t%u correct data packet header prediction%s\n");
	p3(tcps_pcbhashmiss, "\t%u PCB cache miss%s\n");

	p(tcps_ecn_accepts, "\t%u ECN connection%s accepted\n");
	p(tcps_ecn_rcvece, "\t\t%u ECE packet%s received\n");
	p(tcps_ecn_rcvcwr, "\t\t%u CWR packet%s received\n");
	p(tcps_ecn_rcvce, "\t\t%u CE packet%s received\n");
	p(tcps_ecn_sndect, "\t\t%u ECT packet%s sent\n");
	p(tcps_ecn_sndece, "\t\t%u ECE packet%s sent\n");
	p(tcps_ecn_sndcwr, "\t\t%u CWR packet%s sent\n");
	p1(tcps_cwr_frecovery, "\t\t\tcwr by fastrecovery: %u\n");
	p1(tcps_cwr_timeout, "\t\t\tcwr by timeout: %u\n");
	p1(tcps_cwr_ecn, "\t\t\tcwr by ecn: %u\n");

	p(tcps_badsyn, "\t%u bad connection attempt%s\n");
	p1(tcps_sc_added, "\t%qd SYN cache entries added\n");
	p(tcps_sc_collisions, "\t\t%qd hash collision%s\n");
	p1(tcps_sc_completed, "\t\t%qd completed\n");
	p1(tcps_sc_aborted, "\t\t%qd aborted (no space to build PCB)\n");
	p1(tcps_sc_timed_out, "\t\t%qd timed out\n");
	p1(tcps_sc_overflowed, "\t\t%qd dropped due to overflow\n");
	p1(tcps_sc_bucketoverflow, "\t\t%qd dropped due to bucket overflow\n");
	p1(tcps_sc_reset, "\t\t%qd dropped due to RST\n");
	p1(tcps_sc_unreach, "\t\t%qd dropped due to ICMP unreachable\n");
	p(tcps_sc_retransmitted, "\t%qd SYN,ACK%s retransmitted\n");
	p(tcps_sc_dupesyn, "\t%qd duplicate SYN%s received for entries "
		"already in the cache\n");
	p(tcps_sc_dropped, "\t%qd SYN%s dropped (no route or no space)\n");

#undef p
#undef p1
#undef p2
#undef p2a
#undef p3
}
Beispiel #20
0
MenuExample::MenuExample( QWidget *parent, const char *name )
    : QWidget( parent, name )
{
    QPixmap p1( p1_xpm );
    QPixmap p2( p2_xpm );
    QPixmap p3( p3_xpm );

    QPopupMenu *print = new QPopupMenu( this );
    CHECK_PTR( print );
    print->insertTearOffHandle();
    print->insertItem( "&Print to printer", this, SLOT(printer()) );
    print->insertItem( "Print to &file", this, SLOT(file()) );
    print->insertItem( "Print to fa&x", this, SLOT(fax()) );
    print->insertSeparator();
    print->insertItem( "Printer &Setup", this, SLOT(printerSetup()) );

    QPopupMenu *file = new QPopupMenu( this );
    CHECK_PTR( file );
    file->insertItem( p1, "&Open",  this, SLOT(open()), CTRL+Key_O );
    file->insertItem( p2, "&New", this, SLOT(news()), CTRL+Key_N );
    file->insertItem( p3, "&Save", this, SLOT(save()), CTRL+Key_S );
    file->insertItem( "&Close", this, SLOT(closeDoc()), CTRL+Key_W );
    file->insertSeparator();
    file->insertItem( "&Print", print, CTRL+Key_P );
    file->insertSeparator();
    file->insertItem( "E&xit",  qApp, SLOT(quit()), CTRL+Key_Q );

    QPopupMenu *edit = new QPopupMenu( this );
    CHECK_PTR( edit );
    int undoID = edit->insertItem( "&Undo", this, SLOT(undo()) );
    int redoID = edit->insertItem( "&Redo", this, SLOT(redo()) );
    edit->setItemEnabled( undoID, FALSE );
    edit->setItemEnabled( redoID, FALSE );

    QPopupMenu* options = new QPopupMenu( this );
    CHECK_PTR( options );
    options->insertTearOffHandle();
    options->setCaption("Options");
    options->insertItem( "&Normal Font", this, SLOT(normal()) );
    options->insertSeparator();

    options->polish(); // adjust system settings 
    QFont f = options->font();
    f.setBold( TRUE );
    boldID = options->insertItem( new MyMenuItem( "&Bold", f ) );
    options->setAccel( CTRL+Key_B, boldID );
    options->connectItem( boldID, this, SLOT(bold()) );
    f = font();
    f.setUnderline( TRUE );
    underlineID = options->insertItem( new MyMenuItem( "&Underline", f ) );
    options->setAccel( CTRL+Key_U, underlineID );
    options->connectItem( underlineID, this, SLOT(underline()) );

    isBold = FALSE;
    isUnderline = FALSE;
    options->setCheckable( TRUE );


    QPopupMenu *help = new QPopupMenu( this );
    CHECK_PTR( help );
    help->insertItem( "&About", this, SLOT(about()), CTRL+Key_H );
    help->insertItem( "About &Qt", this, SLOT(aboutQt()) );

    menu = new QMenuBar( this );
    CHECK_PTR( menu );
    menu->insertItem( "&File", file );
    menu->insertItem( "&Edit", edit );
    menu->insertItem( "&Options", options );
    menu->insertSeparator();
    menu->insertItem( "&Help", help );
    menu->setSeparator( QMenuBar::InWindowsStyle );

    label = new QLabel( this );
    CHECK_PTR( label );
    label->setGeometry( 20, rect().center().y()-20, width()-40, 40 );
    label->setFrameStyle( QFrame::Box | QFrame::Raised );
    label->setLineWidth( 1 );
    label->setAlignment( AlignCenter );

    connect( this,  SIGNAL(explain(const QString&)),
	     label, SLOT(setText(const QString&)) );

    setMinimumSize( 100, 80 );
}
Beispiel #21
0
// add a pad hole or slot
bool PCBMODEL::AddPadHole( KICADPAD* aPad )
{
    if( NULL == aPad || !aPad->IsThruHole() )
        return false;

    if( !aPad->m_drill.oval )
    {
        TopoDS_Shape s = BRepPrimAPI_MakeCylinder( aPad->m_drill.size.x * 0.5,
            m_thickness * 2.0 ).Shape();
        gp_Trsf shift;
        shift.SetTranslation( gp_Vec( aPad->m_position.x, aPad->m_position.y, -m_thickness * 0.5 ) );
        BRepBuilderAPI_Transform hole( s, shift );
        m_cutouts.push_back( hole.Shape() );
        return true;
    }

    // slotted hole
    double angle_offset = 0.0;
    double rad;     // radius of the slot
    double hlen;    // half length of the slot

    if( aPad->m_drill.size.x < aPad->m_drill.size.y )
    {
        angle_offset = M_PI_2;
        rad = aPad->m_drill.size.x * 0.5;
        hlen = aPad->m_drill.size.y * 0.5 - rad;
    }
    else
    {
        rad = aPad->m_drill.size.y * 0.5;
        hlen = aPad->m_drill.size.x * 0.5 - rad;
    }

    DOUBLET c0( -hlen, 0.0 );
    DOUBLET c1( hlen, 0.0 );
    DOUBLET p0( -hlen, rad );
    DOUBLET p1( -hlen, -rad );
    DOUBLET p2(  hlen, -rad );
    DOUBLET p3( hlen, rad );

    angle_offset += aPad->m_rotation;
    double dlim = (double)std::numeric_limits< float >::epsilon();

    if( angle_offset < -dlim || angle_offset > dlim )
    {
        double vsin = sin( angle_offset );
        double vcos = cos( angle_offset );

        double x = c0.x * vcos - c0.y * vsin;
        double y = c0.x * vsin + c0.y * vcos;
        c0.x = x;
        c0.y = y;

        x = c1.x * vcos - c1.y * vsin;
        y = c1.x * vsin + c1.y * vcos;
        c1.x = x;
        c1.y = y;

        x = p0.x * vcos - p0.y * vsin;
        y = p0.x * vsin + p0.y * vcos;
        p0.x = x;
        p0.y = y;

        x = p1.x * vcos - p1.y * vsin;
        y = p1.x * vsin + p1.y * vcos;
        p1.x = x;
        p1.y = y;

        x = p2.x * vcos - p2.y * vsin;
        y = p2.x * vsin + p2.y * vcos;
        p2.x = x;
        p2.y = y;

        x = p3.x * vcos - p3.y * vsin;
        y = p3.x * vsin + p3.y * vcos;
        p3.x = x;
        p3.y = y;
    }

    c0.x += aPad->m_position.x;
    c0.y += aPad->m_position.y;
    c1.x += aPad->m_position.x;
    c1.y += aPad->m_position.y;
    p0.x += aPad->m_position.x;
    p0.y += aPad->m_position.y;
    p1.x += aPad->m_position.x;
    p1.y += aPad->m_position.y;
    p2.x += aPad->m_position.x;
    p2.y += aPad->m_position.y;
    p3.x += aPad->m_position.x;
    p3.y += aPad->m_position.y;

    OUTLINE oln;
    oln.SetMinSqDistance( m_minDistance2 );
    KICADCURVE crv0, crv1, crv2, crv3;

    // crv0 = arc
    crv0.m_start = c0;
    crv0.m_end = p0;
    crv0.m_ep = p1;
    crv0.m_angle = M_PI;
    crv0.m_radius = rad;
    crv0.m_form = CURVE_ARC;

    // crv1 = line
    crv1.m_start = p1;
    crv1.m_end = p2;
    crv1.m_form = CURVE_LINE;

    // crv2 = arc
    crv2.m_start = c1;
    crv2.m_end = p2;
    crv2.m_ep = p3;
    crv2.m_angle = M_PI;
    crv2.m_radius = rad;
    crv2.m_form = CURVE_ARC;

    // crv3 = line
    crv3.m_start = p3;
    crv3.m_end = p0;
    crv3.m_form = CURVE_LINE;

    oln.AddSegment( crv0 );
    oln.AddSegment( crv1 );
    oln.AddSegment( crv2 );
    oln.AddSegment( crv3 );
    TopoDS_Shape slot;

    if( oln.MakeShape( slot, m_thickness ) )
    {
        if( !slot.IsNull() )
            m_cutouts.push_back( slot );

        return true;
    }

    return false;
}
Beispiel #22
0
int main(int argc, char **argv)
{

	/* initialize constants */

	t   =   0.499975;
	t1  =   0.50025;
	t2  =   2.0;

	/* set values of module weights */

	n1  =   0 * ITERATIONS;
	n2  =  12 * ITERATIONS;
	n3  =  14 * ITERATIONS;
	n4  = 345 * ITERATIONS;
	n6  = 210 * ITERATIONS;
	n7  =  32 * ITERATIONS;
	n8  = 899 * ITERATIONS;
	n9  = 616 * ITERATIONS;
	n10 =   0 * ITERATIONS;
	n11 =  93 * ITERATIONS;

/* MODULE 1:  simple identifiers */

	x1 =  1.0;
	x2 = x3 = x4 = -1.0;

	for(i = 1; i <= n1; i += 1) {
		x1 = ( x1 + x2 + x3 - x4 ) * t;
		x2 = ( x1 + x2 - x3 - x4 ) * t;
		x3 = ( x1 - x2 + x3 + x4 ) * t;
		x4 = (-x1 + x2 + x3 + x4 ) * t;
	}
#ifdef PRINT_RESULTS
	pout(n1, n1, n1, x1, x2, x3, x4);
#endif


/* MODULE 2:  array elements */

	e1[0] =  1.0;
	e1[1] = e1[2] = e1[3] = -1.0;

	for (i = 1; i <= n2; i +=1) {
		e1[0] = ( e1[0] + e1[1] + e1[2] - e1[3] ) * t;
		e1[1] = ( e1[0] + e1[1] - e1[2] + e1[3] ) * t;
		e1[2] = ( e1[0] - e1[1] + e1[2] + e1[3] ) * t;
		e1[3] = (-e1[0] + e1[1] + e1[2] + e1[3] ) * t;
	}
#ifdef PRINT_RESULTS
	pout(n2, n3, n2, e1[0], e1[1], e1[2], e1[3]);
#endif

/* MODULE 3:  array as parameter */

	for (i = 1; i <= n3; i += 1)
		pa(e1);
#ifdef PRINT_RESULTS
	pout(n3, n2, n2, e1[0], e1[1], e1[2], e1[3]);
#endif

/* MODULE 4:  conditional jumps */

	j = 1;
	for (i = 1; i <= n4; i += 1) {
		if (j == 1)
			j = 2;
		else
			j = 3;

		if (j > 2)
			j = 0;
		else
			j = 1;

		if (j < 1 )
			j = 1;
		else
			j = 0;
	}
#ifdef PRINT_RESULTS
	pout(n4, j, j, x1, x2, x3, x4);
#endif

/* MODULE 5:  omitted */

/* MODULE 6:  integer arithmetic */

	j = 1;
	k = 2;
	l = 3;

	for (i = 1; i <= n6; i += 1) {
		j = j * (k - j) * (l -k);
		k = l * k - (l - j) * k;
		l = (l - k) * (k + j);

		e1[l - 2] = j + k + l;		/* C arrays are zero based */
		e1[k - 2] = j * k * l;
	}
#ifdef PRINT_RESULTS
	pout(n6, j, k, e1[0], e1[1], e1[2], e1[3]);
#endif

/* MODULE 7:  trig. functions */

	x = y = 0.5;

	for(i = 1; i <= n7; i +=1) {
		x = t * atan(t2*sin(x)*cos(x)/(cos(x+y)+cos(x-y)-1.0));
		y = t * atan(t2*sin(y)*cos(y)/(cos(x+y)+cos(x-y)-1.0));
	}
#ifdef PRINT_RESULTS
	pout(n7, j, k, x, x, y, y);
#endif

/* MODULE 8:  procedure calls */

	x = y = z = 1.0;

	for (i = 1; i <= n8; i +=1)
		p3(x, y, &z);
#ifdef PRINT_RESULTS
	pout(n8, j, k, x, y, z, z);
#endif

/* MODULE9:  array references */

	j = 1;
	k = 2;
	l = 3;

	e1[0] = 1.0;
	e1[1] = 2.0;
	e1[2] = 3.0;

	for(i = 1; i <= n9; i += 1)
		p0();
#ifdef PRINT_RESULTS
	pout(n9, j, k, e1[0], e1[1], e1[2], e1[3]);
#endif

/* MODULE10:  integer arithmetic */

	j = 2;
	k = 3;

	for(i = 1; i <= n10; i +=1) {
		j = j + k;
		k = j + k;
		j = k - j;
		k = k - j - j;
	}
#ifdef PRINT_RESULTS
	pout(n10, j, k, x1, x2, x3, x4);
#endif

/* MODULE11:  standard functions */

	x = 0.75;
	for(i = 1; i <= n11; i +=1)
		x = sqrt( exp( log(x) / t1));

#ifdef PRINT_RESULTS
	pout(n11, j, k, x, x, x, x);
#endif
        return 0;
}
Beispiel #23
0
template <typename PointT, typename PointNT> bool
pcl::SampleConsensusModelCone<PointT, PointNT>::computeModelCoefficients (
    const std::vector<int> &samples, Eigen::VectorXf &model_coefficients)
{
  // Need 3 samples
  if (samples.size () != 3)
  {
    PCL_ERROR ("[pcl::SampleConsensusModelCone::computeModelCoefficients] Invalid set of samples given (%zu)!\n", samples.size ());
    return (false);
  }

  if (!normals_)
  {
    PCL_ERROR ("[pcl::SampleConsensusModelCone::computeModelCoefficients] No input dataset containing normals was given!\n");
    return (false);
  }

  Eigen::Vector4f p1 (input_->points[samples[0]].x, input_->points[samples[0]].y, input_->points[samples[0]].z, 0);
  Eigen::Vector4f p2 (input_->points[samples[1]].x, input_->points[samples[1]].y, input_->points[samples[1]].z, 0);
  Eigen::Vector4f p3 (input_->points[samples[2]].x, input_->points[samples[2]].y, input_->points[samples[2]].z, 0);

  Eigen::Vector4f n1 (normals_->points[samples[0]].normal[0], normals_->points[samples[0]].normal[1], normals_->points[samples[0]].normal[2], 0);
  Eigen::Vector4f n2 (normals_->points[samples[1]].normal[0], normals_->points[samples[1]].normal[1], normals_->points[samples[1]].normal[2], 0);
  Eigen::Vector4f n3 (normals_->points[samples[2]].normal[0], normals_->points[samples[2]].normal[1], normals_->points[samples[2]].normal[2], 0);

  //calculate apex (intersection of the three planes defined by points and belonging normals
  Eigen::Vector4f ortho12 = n1.cross3(n2);
  Eigen::Vector4f ortho23 = n2.cross3(n3);
  Eigen::Vector4f ortho31 = n3.cross3(n1);

  float denominator = n1.dot(ortho23);

  float d1 = p1.dot (n1);
  float d2 = p2.dot (n2);
  float d3 = p3.dot (n3);

  Eigen::Vector4f apex = (d1 * ortho23 + d2 * ortho31 + d3 * ortho12) / denominator;

  //compute axis (normal of plane defined by: { apex+(p1-apex)/(||p1-apex||), apex+(p2-apex)/(||p2-apex||), apex+(p3-apex)/(||p3-apex||)}
  Eigen::Vector4f ap1 = p1 - apex;
  Eigen::Vector4f ap2 = p2 - apex;
  Eigen::Vector4f ap3 = p3 - apex;

  Eigen::Vector4f np1 = apex + (ap1/ap1.norm ());
  Eigen::Vector4f np2 = apex + (ap2/ap2.norm ());
  Eigen::Vector4f np3 = apex + (ap3/ap3.norm ());

  Eigen::Vector4f np1np2 = np2 - np1;
  Eigen::Vector4f np1np3 = np3 - np1;

  Eigen::Vector4f axis_dir = np1np2.cross3 (np1np3);
  axis_dir.normalize ();

  // normalize the vector (apex->p) for opening angle calculation
  ap1.normalize ();
  ap2.normalize ();
  ap3.normalize ();

  //compute opening angle
  float opening_angle = ( acosf (ap1.dot (axis_dir)) + acosf (ap2.dot (axis_dir)) + acosf (ap3.dot (axis_dir)) ) / 3.0f;

  model_coefficients.resize (7);
  // model_coefficients.template head<3> ()    = line_pt.template head<3> ();
  model_coefficients[0] = apex[0];
  model_coefficients[1] = apex[1];
  model_coefficients[2] = apex[2];
  // model_coefficients.template segment<3> (3) = line_dir.template head<3> ();
  model_coefficients[3] = axis_dir[0];
  model_coefficients[4] = axis_dir[1];
  model_coefficients[5] = axis_dir[2];
  // cone radius
  model_coefficients[6] = opening_angle;

  if (model_coefficients[6] != -std::numeric_limits<double>::max() && model_coefficients[6] < min_angle_)
    return (false);
  if (model_coefficients[6] !=  std::numeric_limits<double>::max() && model_coefficients[6] > max_angle_)
    return (false);

  return (true);
}
Beispiel #24
0
void Sphere::paint(void)
{
    float thetaRange = 2*PI;
    float phiRange   = PI;
    float thetaStart = 0.0;
    float phiStart = -PI/2.0;
    float thetaDelta = thetaRange / mThetaSteps;
    float phiDelta = phiRange / mPhiSteps;

    mMaterial->glSetMaterial();

    int i;
    int j;
    glBegin(GL_QUADS);
    for (i = 0; i < mPhiSteps; i++)
    for (j = 0; j < mThetaSteps; j++)
    {
        // compute appropriate coordinates & normals
        float curPhi = i * phiDelta;
        float curTheta = j * thetaDelta;
        float nextPhi = (i + 1) * phiDelta;
        float nextTheta = (j + 1) * thetaDelta;

        Vec3f p0(mRadius * sin(curTheta) * cos(curPhi),
                 mRadius * sin(curTheta) * sin(curPhi),
                 mRadius * cos(curTheta));

        p0 += mCenterPoint;
        Vec3f n0 = p0 - mCenterPoint;
        n0.Normalize();

        Vec3f p1(mRadius * sin(curTheta) * cos(nextPhi),
                 mRadius * sin(curTheta) * sin(nextPhi),
                 mRadius * cos(curTheta));

        p1 += mCenterPoint;
        Vec3f n1 = p1 - mCenterPoint;
        n1.Normalize();

        Vec3f p2(mRadius * sin(nextTheta) * cos(curPhi),
                 mRadius * sin(nextTheta) * sin(curPhi),
                 mRadius * cos(nextTheta));

        p2 += mCenterPoint;
        Vec3f n2 = p2 - mCenterPoint;
        n2.Normalize();

        Vec3f p3(mRadius * sin(nextTheta) * cos(nextPhi),
                 mRadius * sin(nextTheta) * sin(nextPhi),
                 mRadius * cos(nextTheta));

        p3 += mCenterPoint;
        Vec3f n3 = p3 - mCenterPoint;
        n3.Normalize();

        //Actually, what I have done is just the Gourand shading, four normals for
        //the polygon
        glNormal3f(n0.x(), n0.y(), n0.z());
        glVertex3f(p0.x(), p0.y(), p0.z());

        glNormal3f(n1.x(), n1.y(), n1.z());
        glVertex3f(p1.x(), p1.y(), p1.z());
        
        glNormal3f(n3.x(), n3.y(), n3.z());
        glVertex3f(p3.x(), p3.y(), p3.z());
        
        glNormal3f(n2.x(), n2.y(), n2.z());
        glVertex3f(p2.x(), p2.y(), p2.z());
    }
    glEnd();
}
Beispiel #25
0
    void AngleBendContrib::getGrad(double *pos,double *grad) const {
      PRECONDITION(dp_forceField,"no owner");
      PRECONDITION(pos,"bad vector");
      PRECONDITION(grad,"bad vector");

      double dist1=this->dp_forceField->distance(this->d_at1Idx,this->d_at2Idx,pos);
      double dist2=this->dp_forceField->distance(this->d_at2Idx,this->d_at3Idx,pos);

      //std::cout << "\tAngle("<<this->d_at1Idx<<","<<this->d_at2Idx<<","<<this->d_at3Idx<<") " << dist1 << " " << dist2 << std::endl;
      
      RDGeom::Point3D p1(pos[3*this->d_at1Idx],
       pos[3*this->d_at1Idx+1],
       pos[3*this->d_at1Idx+2]);
      RDGeom::Point3D p2(pos[3*this->d_at2Idx],
       pos[3*this->d_at2Idx+1],
       pos[3*this->d_at2Idx+2]);
      RDGeom::Point3D p3(pos[3*this->d_at3Idx],
       pos[3*this->d_at3Idx+1],
       pos[3*this->d_at3Idx+2]);
      double *g1=&(grad[3*this->d_at1Idx]);
      double *g2=&(grad[3*this->d_at2Idx]);
      double *g3=&(grad[3*this->d_at3Idx]);

      RDGeom::Point3D p12=p1-p2;
      RDGeom::Point3D p32=p3-p2;
      double cosTheta = p12.dotProduct(p32)/(dist1*dist2);
      double sinTheta = std::max(sqrt(1.0-cosTheta*cosTheta),1e-8);

      //std::cerr << "GRAD: " << cosTheta << " (" << acos(cosTheta)<< "), ";
      //std::cerr << sinTheta << " (" << asin(sinTheta)<< ")" << std::endl;
    
      // use the chain rule:
      // dE/dx = dE/dTheta * dTheta/dx

      // dE/dTheta is independent of cartesians:
      double dE_dTheta=getThetaDeriv(cosTheta,sinTheta);
    
      // -------
      // dTheta/dx is trickier:
      double dCos_dS1=1./dist1 * (p32.x/dist2 - cosTheta*p12.x/dist1);
      double dCos_dS2=1./dist1 * (p32.y/dist2 - cosTheta*p12.y/dist1);
      double dCos_dS3=1./dist1 * (p32.z/dist2 - cosTheta*p12.z/dist1);

      double dCos_dS4=1./dist2 * (p12.x/dist1 - cosTheta*p32.x/dist2);
      double dCos_dS5=1./dist2 * (p12.y/dist1 - cosTheta*p32.y/dist2);
      double dCos_dS6=1./dist2 * (p12.z/dist1 - cosTheta*p32.z/dist2);

    
      g1[0] += dE_dTheta*dCos_dS1/(-sinTheta);
      g1[1] += dE_dTheta*dCos_dS2/(-sinTheta);
      g1[2] += dE_dTheta*dCos_dS3/(-sinTheta);

      g2[0] += dE_dTheta*(-dCos_dS1 - dCos_dS4)/(-sinTheta);
      g2[1] += dE_dTheta*(-dCos_dS2 - dCos_dS5)/(-sinTheta);
      g2[2] += dE_dTheta*(-dCos_dS3 - dCos_dS6)/(-sinTheta);
    
      g3[0] += dE_dTheta*dCos_dS4/(-sinTheta);
      g3[1] += dE_dTheta*dCos_dS5/(-sinTheta);
      g3[2] += dE_dTheta*dCos_dS6/(-sinTheta);

    }
Beispiel #26
0
/**
 * メッシュ情報を読み込む
 *
 * @param mesh メッシュ情報
 */
void FbxFileLoader::load_mesh( FbxMesh* mesh )
{
	if ( ! mesh )
	{
		return;
	}

	if ( ! get_model()->get_mesh() )
	{
		get_model()->set_mesh( create_mesh() );
	}

	VertexIndexMap vertex_index_map;
	VertexList vertex_list;

	Mesh::PositionList position_list;
	Mesh::VertexWeightList vertex_weight_list;

	// load_mesh_vertex()
	for ( int n = 0; n < mesh->GetControlPointsCount(); n++ )
	{
		FbxVector4 v = mesh->GetControlPointAt( n );

		position_list.push_back(
			Mesh::Position(
				static_cast< float >( v[ 0 ] ),
				static_cast< float >( v[ 1 ] ),
				static_cast< float >( v[ 2 ] ) ) );
	}

	// load_mesh_vertex_weight()
	{
		int skin_count = mesh->GetDeformerCount( FbxDeformer::eSkin );

		if ( skin_count > 0 )
		{
			assert( skin_count == 1 );

			vertex_weight_list.resize( position_list.size() );

			FbxSkin* skin = FbxCast< FbxSkin >( mesh->GetDeformer( 0, FbxDeformer::eSkin ) );

			load_mesh_vertex_weight( skin, vertex_weight_list );
		}
	}

	FbxLayerElementSmoothing* smoothing = 0;

	// load_mesh_smoothing_info()
	{
		FbxLayer* layer = mesh->GetLayer( 0 );
		smoothing = layer->GetSmoothing();
	}

	if ( ! smoothing )
	{
		COMMON_THROW_EXCEPTION_MESSAGE( "this FBX format is not supported. ( no smoothing info )" );
	}

	// load_mesh_plygon()
	FbxLayerElementArrayTemplate< int >* material_indices;
	mesh->GetMaterialIndices( & material_indices );

	for ( int n = 0; n < mesh->GetPolygonCount(); n++ )
	{
		Mesh::VertexGroup* vertex_group = get_model()->get_mesh()->get_vertex_group_at( material_indices->GetAt( n ) );

		bool is_smooth = smoothing->GetDirectArray().GetAt( n ) != 0;
		FbxVector4 polygon_normal( 0.f, 0.f, 0.f );

		if ( ! is_smooth )
		{
			// ポリゴンの法線を計算する
			Mesh::Position p1( position_list.at( mesh->GetPolygonVertex( n, 0 ) ) );
			Mesh::Position p2( position_list.at( mesh->GetPolygonVertex( n, 1 ) ) );
			Mesh::Position p3( position_list.at( mesh->GetPolygonVertex( n, 2 ) ) );

			FbxVector4 a = FbxVector4( p1.x(), p1.y(), p1.z() );
			FbxVector4 b = FbxVector4( p2.x(), p2.y(), p2.z() );
			FbxVector4 c = FbxVector4( p3.x(), p3.y(), p3.z() );

			FbxVector4 ab( b - a );
			FbxVector4 bc( c - b );

			polygon_normal = ab.CrossProduct( bc );
			polygon_normal.Normalize();
		}

		for ( int m = 0; m < mesh->GetPolygonSize( n ); m++ )
		{
			int position_index = mesh->GetPolygonVertex( n, m );

			Mesh::Vertex v;
			v.Position = Mesh::Position( position_list.at( position_index ) );

			FbxVector2 uv_vector;
			bool unmapped;
			
			if ( mesh->GetPolygonVertexUV( n, m, "UVMap", uv_vector, unmapped) )
			{
				v.TexCoord = Mesh::TexCoord(
					static_cast< float >( uv_vector[ 0 ] ),
					1.f - static_cast< float >( uv_vector[ 1 ] ) );
			}

			if ( is_smooth )
			{
				FbxVector4 normal_vector;

				// 頂点の法線
				if ( mesh->GetPolygonVertexNormal( n, m, normal_vector ) )
				{
					v.Normal = Mesh::Normal(
						static_cast< float >( normal_vector[ 0 ] ),
						static_cast< float >( normal_vector[ 1 ] ),
						static_cast< float >( normal_vector[ 2 ] ) );
				}
			}
			else
			{
				// ポリゴンの法線
				v.Normal = Mesh::Normal(
					static_cast< float >( polygon_normal[ 0 ] ),
					static_cast< float >( polygon_normal[ 1 ] ),
					static_cast< float >( polygon_normal[ 2 ] ) );
			}
			
			// 頂点の一覧に追加
			{
				VertexIndexMap::iterator i = vertex_index_map.find( v );

				if ( i != vertex_index_map.end() )
				{
					vertex_group->add_index( i->second );
				}
				else
				{
					Mesh::Index vertex_index = static_cast< Mesh::Index >( get_model()->get_mesh()->get_vertex_count() );

					get_model()->get_mesh()->add_vertex( v );

					if ( ! vertex_weight_list.empty() )
					{
						get_model()->get_mesh()->add_vertex_weight( vertex_weight_list.at( position_index ) );
					}

					vertex_group->add_index( vertex_index );

					vertex_index_map[ v ] = vertex_index;
				}
			}
		}
	}
}
Beispiel #27
0
void Tie::computeBezier(SlurSegment* ss, QPointF p6o)
      {
      qreal _spatium  = spatium();
      qreal shoulderW;              // height as fraction of slur-length
      qreal shoulderH;

      //
      // pp1      start of slur
      // pp2      end of slur
      // pp3      bezier 1
      // pp4      bezier 2
      // pp5      drag
      // pp6      shoulder
      //
      QPointF pp1 = ss->ups[GRIP_START].p + ss->ups[GRIP_START].off * _spatium;
      QPointF pp2 = ss->ups[GRIP_END].p   + ss->ups[GRIP_END].off   * _spatium;

      QPointF p2 = pp2 - pp1;       // normalize to zero
      if (p2.x() == 0.0) {
            qDebug("zero tie");
            return;
            }

      qreal sinb = atan(p2.y() / p2.x());
      QTransform t;
      t.rotateRadians(-sinb);
      p2  = t.map(p2);
      p6o = t.map(p6o);

      double smallH = 0.38;
      qreal d   = p2.x() / _spatium;
      shoulderH = d * 0.4 * smallH;
      if (shoulderH > 1.3)            // maximum tie shoulder height
            shoulderH = 1.3;
      shoulderH *= _spatium;
      shoulderW = .6;

      shoulderH -= p6o.y();

      if (!up())
            shoulderH = -shoulderH;

      qreal c    = p2.x();
      qreal c1   = (c - c * shoulderW) * .5 + p6o.x();
      qreal c2   = c1 + c * shoulderW       + p6o.x();

      QPointF p5 = QPointF(c * .5, 0.0);

      QPointF p3(c1, -shoulderH);
      QPointF p4(c2, -shoulderH);

      qreal w = (score()->styleS(ST_SlurMidWidth).val() - score()->styleS(ST_SlurEndWidth).val()) * _spatium;
      QPointF th(0.0, w);    // thickness of slur

      QPointF p3o = p6o + t.map(ss->ups[GRIP_BEZIER1].off * _spatium);
      QPointF p4o = p6o + t.map(ss->ups[GRIP_BEZIER2].off * _spatium);

      if(!p6o.isNull()) {
            QPointF p6i = t.inverted().map(p6o) / _spatium;
            ss->ups[GRIP_BEZIER1].off += p6i ;
            ss->ups[GRIP_BEZIER2].off += p6i;
            }

      //-----------------------------------calculate p6
      QPointF pp3  = p3 + p3o;
      QPointF pp4  = p4 + p4o;
      QPointF ppp4 = pp4 - pp3;

      qreal r2 = atan(ppp4.y() / ppp4.x());
      t.reset();
      t.rotateRadians(-r2);
      QPointF p6  = QPointF(t.map(ppp4).x() * .5, 0.0);

      t.rotateRadians(2 * r2);
      p6 = t.map(p6) + pp3 - p6o;
      //-----------------------------------

      ss->path = QPainterPath();
      ss->path.moveTo(QPointF());
      ss->path.cubicTo(p3 + p3o - th, p4 + p4o - th, p2);
      if (lineType() == 0)
            ss->path.cubicTo(p4 +p4o + th, p3 + p3o + th, QPointF());

      th = QPointF(0.0, 3.0 * w);
      ss->shapePath = QPainterPath();
      ss->shapePath.moveTo(QPointF());
      ss->shapePath.cubicTo(p3 + p3o - th, p4 + p4o - th, p2);
      ss->shapePath.cubicTo(p4 +p4o + th, p3 + p3o + th, QPointF());

      // translate back
      t.reset();
      t.translate(pp1.x(), pp1.y());
      t.rotateRadians(sinb);
      ss->path                 = t.map(ss->path);
      ss->shapePath            = t.map(ss->shapePath);
      ss->ups[GRIP_BEZIER1].p  = t.map(p3);
      ss->ups[GRIP_BEZIER2].p  = t.map(p4);
      ss->ups[GRIP_END].p      = t.map(p2) - ss->ups[GRIP_END].off * _spatium;
      ss->ups[GRIP_DRAG].p     = t.map(p5);
      ss->ups[GRIP_SHOULDER].p = t.map(p6);
      }
Beispiel #28
0
void OpenPSTD::GUI::DGResults::UpdateScene(const std::shared_ptr<OpenPSTD::GUI::Model> &m,
                                           std::unique_ptr<QOpenGLFunctions, void (*)(void *)> const &f)
{
    program->bind();

    if(m->view->IsChanged())
    {
        program->setUniformValue("u_view", m->view->viewMatrix);
    }

    auto doc = m->documentAccess->GetDocument();

    if(m->interactive->visibleFrame >= 0 && m->interactive->visibleFrame < doc->GetResultsDGFrameCount())
    {
        if (m->documentAccess->IsChanged())
        {
            auto conf = doc->GetResultsSceneConf();

            std::vector<QVector2D> positions;
            positions.reserve(conf->DGIndices.size() * 3);
            MinMaxValue minMaxPos;

            for (int i = 0; i < conf->DGIndices.size(); ++i)
            {
                //create the 3 points
                QVector2D p1(conf->DGVertices[conf->DGIndices[i][0]](0),
                             conf->DGVertices[conf->DGIndices[i][0]](1));
                QVector2D p2(conf->DGVertices[conf->DGIndices[i][1]](0),
                             conf->DGVertices[conf->DGIndices[i][1]](1));
                QVector2D p3(conf->DGVertices[conf->DGIndices[i][2]](0),
                             conf->DGVertices[conf->DGIndices[i][2]](1));

                //update min max values
                minMaxPos = MinMaxValue::Combine(minMaxPos, MinMaxValue(p1, p2));

                //add to vector
                positions.push_back(p1);
                positions.push_back(p2);
                positions.push_back(p3);
            }
            triangles = conf->DGIndices.size();

            this->minMaxPos = minMaxPos;

            f->glBindBuffer(GL_ARRAY_BUFFER, this->positionsBuffer);
            f->glBufferData(GL_ARRAY_BUFFER, positions.size() * sizeof(QVector2D), positions.data(), GL_STATIC_DRAW);
        }

        if (m->interactive->IsChanged())
        {
            Kernel::DG_FRAME_PTR frame = doc->GetResultsDGFrameCorner(m->interactive->visibleFrame);

            std::vector<float> values(frame->rows() * frame->cols());
            Eigen::Map<Kernel::DG_FRAME> map(values.data(), frame->rows(), frame->cols());

            map = *frame;

            f->glBindBuffer(GL_ARRAY_BUFFER, this->valuesBuffer);
            f->glBufferData(GL_ARRAY_BUFFER, values.size() * sizeof(float), values.data(), GL_DYNAMIC_DRAW);
            valuesInitialized = true;
        }
    }
}
  void serialization_test()
  {
    std::string file("test");

    bool tbIn = true,tbOut;
    char tcIn = 't',tcOut;
    unsigned char tucIn = 'u',tucOut;
    short tsIn = 6,tsOut;
    int tiIn = -10,tiOut;
    unsigned int tuiIn = 10,tuiOut;
    float tfIn = 1.0005,tfOut;
    double tdIn = 1.000000005,tdOut;

    int* tinpIn = NULL,*tinpOut = NULL;
    float* tfpIn = new float,*tfpOut = NULL;
    *tfpIn = 1.11101;

    std::string tstrIn("test12345"),tstrOut;

    Test2 tObjIn,tObjOut;
    int ti = 2;
    tObjIn.ti = &ti;


    Test1 test1,test2,test3;
    test1.ts = "100";
    test2.ts = "200";
    test3.ts = "300";

    Test1 testA, testC;
    testA.tt = &test1;
    testA.ts = "test123";
    testA.tvt.push_back(&test2);
    testA.tvt.push_back(&test3);

    Test1 testB = testA;
    testB.ts = "400";
    testB.tvt.pop_back();

    std::pair<int,bool> tPairIn(10,true);
    std::pair<int,bool> tPairOut;

    std::vector<int> tVector1In ={1,2,3,4,5};
    std::vector<int> tVector1Out;

    std::pair<int,bool> p1(10,1);
    std::pair<int,bool> p2(1,0);
    std::pair<int,bool> p3(10000,1);
    std::vector<std::pair<int,bool> > tVector2In ={p1,p2,p3};
    std::vector<std::pair<int,bool> > tVector2Out;

    std::set<std::pair<int,bool> > tSetIn ={p1,p2,p3};
    std::set<std::pair<int,bool> > tSetOut;

    std::map<int,bool> tMapIn ={p1,p2,p3};
    std::map<int,bool> tMapOut;

    Eigen::Matrix<float,3,3> tDenseMatrixIn;
    tDenseMatrixIn << Eigen::Matrix<float,3,3>::Random();
    tDenseMatrixIn.coeffRef(0,0) = 1.00001;
    Eigen::Matrix<float,3,3> tDenseMatrixOut;

    Eigen::Matrix<float,3,3,Eigen::RowMajor> tDenseRowMatrixIn;
    tDenseRowMatrixIn << Eigen::Matrix<float,3,3,Eigen::RowMajor>::Random();
    Eigen::Matrix<float,3,3,Eigen::RowMajor> tDenseRowMatrixOut;

    Eigen::SparseMatrix<double> tSparseMatrixIn;
    tSparseMatrixIn.resize(3,3);
    tSparseMatrixIn.insert(0,0) = 1.3;
    tSparseMatrixIn.insert(1,1) = 10.2;
    tSparseMatrixIn.insert(2,2) = 100.1;
    tSparseMatrixIn.finalize();
    Eigen::SparseMatrix<double> tSparseMatrixOut;

    // binary serialization

    igl::serialize(tbIn,file);
    igl::deserialize(tbOut,file);
    assert(tbIn == tbOut);

    igl::serialize(tcIn,file);
    igl::deserialize(tcOut,file);
    assert(tcIn == tcOut);

    igl::serialize(tucIn,file);
    igl::deserialize(tucOut,file);
    assert(tucIn == tucOut);

    igl::serialize(tsIn,file);
    igl::deserialize(tsOut,file);
    assert(tsIn == tsOut);

    igl::serialize(tiIn,file);
    igl::deserialize(tiOut,file);
    assert(tiIn == tiOut);

    igl::serialize(tuiIn,file);
    igl::deserialize(tuiOut,file);
    assert(tuiIn == tuiOut);

    igl::serialize(tfIn,file);
    igl::deserialize(tfOut,file);
    assert(tfIn == tfOut);

    igl::serialize(tdIn,file);
    igl::deserialize(tdOut,file);
    assert(tdIn == tdOut);

    igl::serialize(tinpIn,file);
    igl::deserialize(tinpOut,file);
    assert(tinpIn == tinpOut);

    igl::serialize(tfpIn,file);
    igl::deserialize(tfpOut,file);
    assert(*tfpIn == *tfpOut);
    tfpOut = NULL;

    igl::serialize(tstrIn,file);
    igl::deserialize(tstrOut,file);
    assert(tstrIn == tstrOut);

    // updating
    igl::serialize(tbIn,"tb",file,true);
    igl::serialize(tcIn,"tc",file);
    igl::serialize(tiIn,"ti",file);
    tiIn++;
    igl::serialize(tiIn,"ti",file);
    tiIn++;
    igl::serialize(tiIn,"ti",file);
    igl::deserialize(tbOut,"tb",file);
    igl::deserialize(tcOut,"tc",file);
    igl::deserialize(tiOut,"ti",file);
    assert(tbIn == tbOut);
    assert(tcIn == tcOut);
    assert(tiIn == tiOut);

    igl::serialize(tsIn,"tsIn",file,true);
    igl::serialize(tVector1In,"tVector1In",file);
    igl::serialize(tVector2In,"tsIn",file);
    igl::deserialize(tVector2Out,"tsIn",file);
    for(unsigned int i=0;i<tVector2In.size();i++)
    {
      assert(tVector2In[i].first == tVector2Out[i].first);
      assert(tVector2In[i].second == tVector2Out[i].second);
    }
    tVector2Out.clear();

    igl::serialize(tObjIn,file);
    igl::deserialize(tObjOut,file);
    assert(tObjIn.tc == tObjOut.tc);
    assert(*tObjIn.ti == *tObjOut.ti);
    for(unsigned int i=0;i<tObjIn.tvb.size();i++)
      assert(tObjIn.tvb[i] == tObjOut.tvb[i]);
    tObjOut.ti = NULL;

    igl::serialize(tPairIn,file);
    igl::deserialize(tPairOut,file);
    assert(tPairIn.first == tPairOut.first);
    assert(tPairIn.second == tPairOut.second);

    igl::serialize(tVector1In,file);
    igl::deserialize(tVector1Out,file);
    for(unsigned int i=0;i<tVector1In.size();i++)
      assert(tVector1In[i] == tVector1Out[i]);

    igl::serialize(tVector2In,file);
    igl::deserialize(tVector2Out,file);
    for(unsigned int i=0;i<tVector2In.size();i++)
    {
      assert(tVector2In[i].first == tVector2Out[i].first);
      assert(tVector2In[i].second == tVector2Out[i].second);
    }

    igl::serialize(tSetIn,file);
    igl::deserialize(tSetOut,file);
    assert(tSetIn.size() == tSetOut.size());

    igl::serialize(tMapIn,file);
    igl::deserialize(tMapOut,file);
    assert(tMapIn.size() == tMapOut.size());

    igl::serialize(tDenseMatrixIn,file);
    igl::deserialize(tDenseMatrixOut,file);
    assert((tDenseMatrixIn - tDenseMatrixOut).sum() == 0);

    igl::serialize(tDenseRowMatrixIn,file);
    igl::deserialize(tDenseRowMatrixOut,file);
    assert((tDenseRowMatrixIn - tDenseRowMatrixOut).sum() == 0);

    igl::serialize(tSparseMatrixIn,file);
    igl::deserialize(tSparseMatrixOut,file);
    assert((tSparseMatrixIn - tSparseMatrixOut).sum() == 0);

    igl::serialize(testB,file);
    igl::deserialize(testC,file);
    assert(testB.ts == testC.ts);
    assert(testB.tvt.size() == testC.tvt.size());
    for(unsigned int i=0;i<testB.tvt.size();i++)
    {
      assert(testB.tvt[i]->ts == testC.tvt[i]->ts);
      assert(testB.tvt[i]->tvt.size() == testC.tvt[i]->tvt.size());
      assert(testB.tvt[i]->tt == testC.tvt[i]->tt);
    }
    assert(testB.tt->ts == testC.tt->ts);
    assert(testB.tt->tvt.size() == testC.tt->tvt.size());
    assert(testB.tt->tt == testC.tt->tt);
    testC = Test1();

    // big data test
    /*std::vector<std::vector<float> > bigDataIn,bigDataOut;
    for(unsigned int i=0;i<10000;i++)
    {
    std::vector<float> v;
    for(unsigned int j=0;j<10000;j++)
    {
    v.push_back(j);
    }
    bigDataIn.push_back(v);
    }

    igl::Timer timer;
    timer.start();
    igl::serialize(bigDataIn,file);
    timer.stop();
    std::cout << "ser: " << timer.getElapsedTimeInMilliSec() << std::endl;

    timer.start();
    igl::deserialize(bigDataOut,file);
    timer.stop();
    std::cout << "des: " << timer.getElapsedTimeInMilliSec() << std::endl;
    char c;
    std::cin >> c; */

    // xml serialization

    igl::serialize_xml(tbIn,file);
    igl::deserialize_xml(tbOut,file);
    assert(tbIn == tbOut);

    igl::serialize_xml(tcIn,file);
    igl::deserialize_xml(tcOut,file);
    assert(tcIn == tcOut);

    igl::serialize_xml(tucIn,file);
    igl::deserialize_xml(tucOut,file);
    assert(tucIn == tucOut);

    igl::serialize_xml(tsIn,file);
    igl::deserialize_xml(tsOut,file);
    assert(tsIn == tsOut);

    igl::serialize_xml(tiIn,file);
    igl::deserialize_xml(tiOut,file);
    assert(tiIn == tiOut);

    igl::serialize_xml(tuiIn,file);
    igl::deserialize_xml(tuiOut,file);
    assert(tuiIn == tuiOut);

    igl::serialize_xml(tfIn,file);
    igl::deserialize_xml(tfOut,file);
    assert(tfIn == tfOut);

    igl::serialize_xml(tdIn,file);
    igl::deserialize_xml(tdOut,file);
    assert(tdIn == tdOut);

    igl::serialize_xml(tinpIn,file);
    igl::deserialize_xml(tinpOut,file);
    assert(tinpIn == tinpOut);

    igl::serialize_xml(tfpIn,file);
    igl::deserialize_xml(tfpOut,file);
    assert(*tfpIn == *tfpOut);

    igl::serialize_xml(tstrIn,file);
    igl::deserialize_xml(tstrOut,file);
    assert(tstrIn == tstrOut);

    // updating
    igl::serialize_xml(tbIn,"tb",file,false,true);
    igl::serialize_xml(tcIn,"tc",file);
    igl::serialize_xml(tiIn,"ti",file);
    tiIn++;
    igl::serialize_xml(tiIn,"ti",file);
    tiIn++;
    igl::serialize_xml(tiIn,"ti",file);
    igl::deserialize_xml(tbOut,"tb",file);
    igl::deserialize_xml(tcOut,"tc",file);
    igl::deserialize_xml(tiOut,"ti",file);
    assert(tbIn == tbOut);
    assert(tcIn == tcOut);
    assert(tiIn == tiOut);

    igl::serialize_xml(tsIn,"tsIn",file,false,true);
    igl::serialize_xml(tVector1In,"tVector1In",file);
    igl::serialize_xml(tVector2In,"tsIn",file);
    igl::deserialize_xml(tVector2Out,"tsIn",file);
    for(unsigned int i=0;i<tVector2In.size();i++)
    {
      assert(tVector2In[i].first == tVector2Out[i].first);
      assert(tVector2In[i].second == tVector2Out[i].second);
    }
    tVector2Out.clear();

    // binarization
    igl::serialize_xml(tVector2In,"tVector2In",file,true);
    igl::deserialize_xml(tVector2Out,"tVector2In",file);
    for(unsigned int i=0;i<tVector2In.size();i++)
    {
      assert(tVector2In[i].first == tVector2Out[i].first);
      assert(tVector2In[i].second == tVector2Out[i].second);
    }

    igl::serialize_xml(tObjIn,file);
    igl::deserialize_xml(tObjOut,file);
    assert(tObjIn.tc == tObjOut.tc);
    assert(*tObjIn.ti == *tObjOut.ti);
    for(unsigned int i=0;i<tObjIn.tvb.size();i++)
      assert(tObjIn.tvb[i] == tObjOut.tvb[i]);

    igl::serialize_xml(tPairIn,file);
    igl::deserialize_xml(tPairOut,file);
    assert(tPairIn.first == tPairOut.first);
    assert(tPairIn.second == tPairOut.second);

    igl::serialize_xml(tVector1In,file);
    igl::deserialize_xml(tVector1Out,file);
    for(unsigned int i=0;i<tVector1In.size();i++)
      assert(tVector1In[i] == tVector1Out[i]);

    igl::serialize_xml(tVector2In,file);
    igl::deserialize_xml(tVector2Out,file);
    for(unsigned int i=0;i<tVector2In.size();i++)
    {
      assert(tVector2In[i].first == tVector2Out[i].first);
      assert(tVector2In[i].second == tVector2Out[i].second);
    }

    igl::serialize_xml(tSetIn,file);
    igl::deserialize_xml(tSetOut,file);
    assert(tSetIn.size() == tSetOut.size());

    igl::serialize_xml(tMapIn,file);
    igl::deserialize_xml(tMapOut,file);
    assert(tMapIn.size() == tMapOut.size());

    igl::serialize_xml(tDenseMatrixIn,file);
    igl::deserialize_xml(tDenseMatrixOut,file);
    assert((tDenseMatrixIn - tDenseMatrixOut).sum() == 0);

    igl::serialize_xml(tDenseRowMatrixIn,file);
    igl::deserialize_xml(tDenseRowMatrixOut,file);
    assert((tDenseRowMatrixIn - tDenseRowMatrixOut).sum() == 0);

    igl::serialize_xml(tSparseMatrixIn,file);
    igl::deserialize_xml(tSparseMatrixOut,file);
    assert((tSparseMatrixIn - tSparseMatrixOut).sum() == 0);

    igl::serialize_xml(testB,file);
    igl::deserialize_xml(testC,file);
    assert(testB.ts == testC.ts);
    assert(testB.tvt.size() == testC.tvt.size());
    for(unsigned int i=0;i<testB.tvt.size();i++)
    {
      assert(testB.tvt[i]->ts == testC.tvt[i]->ts);
      assert(testB.tvt[i]->tvt.size() == testC.tvt[i]->tvt.size());
      assert(testB.tvt[i]->tt == testC.tvt[i]->tt);
    }
    assert(testB.tt->ts == testC.tt->ts);
    assert(testB.tt->tvt.size() == testC.tt->tvt.size());
    assert(testB.tt->tt == testC.tt->tt);

    // big data test
    /*std::vector<std::vector<float> > bigDataIn,bigDataOut;
    for(unsigned int i=0;i<10000;i++)
    {
    std::vector<float> v;
    for(unsigned int j=0;j<10000;j++)
    {
    v.push_back(j);
    }
    bigDataIn.push_back(v);
    }

    igl::Timer timer;
    timer.start();
    igl::serialize_xml(bigDataIn,"bigDataIn",file,igl::SERIALIZE_BINARY);
    timer.stop();
    std::cout << "ser: " << timer.getElapsedTimeInMilliSec() << std::endl;

    timer.start();
    igl::deserialize_xml(bigDataOut,"bigDataIn",file);
    timer.stop();
    std::cout << "des: " << timer.getElapsedTimeInMilliSec() << std::endl;
    char c;
    std::cin >> c;*/

    std::cout << "All tests run successfully!\n";
  }
Beispiel #30
0
std::shared_ptr<Mesh<Vertex3DNormTex>> MeshConstructor::constructConvexPolygonMesh(const std::vector<Vertex3DNormTex> &vertices, const glm::vec3 &axis1, const glm::vec3 &axis2, const glm::vec3 rotation, float accuracy)
{
	std::shared_ptr<Mesh<Vertex3DNormTex>> mesh(std::make_shared<Mesh<Vertex3DNormTex>>());

	glm::mat3x2 projection = glm::transpose(glm::mat2x3(axis1, axis2));
	std::vector<glm::ivec2> positions;
	std::vector<glm::vec2> uniquePositions;
	std::vector<int> convexHullPositions;
	glm::vec2 middlePoint;
	Box meshBounds(glm::vec3(std::numeric_limits<float>::infinity()), -glm::vec3(std::numeric_limits<float>::infinity()));
	int startPointIndex = 0;
	int nextPointIndex = 0;

	glm::mat4 transformation(1);
	transformation = glm::rotate(transformation, rotation.x, glm::vec3(1, 0, 0));
	transformation = glm::rotate(transformation, rotation.y, glm::vec3(0, 1, 0));
	transformation = glm::rotate(transformation, rotation.z, glm::vec3(0, 0, 1));

	std::vector<glm::vec2> boundVertices;
	for (int i = 0; i < 4; ++i)
	{
		boundVertices.push_back(projection * glm::vec3(transformation * glm::vec4(vertices[0].m_position, 1)));
	}

	for (unsigned int vertexIndex = 0; vertexIndex < vertices.size(); ++vertexIndex)
	{
		glm::vec2 projectedPosition = projection * glm::vec3(transformation * glm::vec4(vertices[vertexIndex].m_position, 1));
		if (boundVertices[0].x > projectedPosition.x)
		{
			boundVertices[0] = projectedPosition;
		}
		if (boundVertices[1].y > projectedPosition.y)
		{
			boundVertices[1] = projectedPosition;
		}
		if (boundVertices[2].x < projectedPosition.x)
		{
			boundVertices[2] = projectedPosition;
		}
		if (boundVertices[3].y < projectedPosition.y)
		{
			boundVertices[3] = projectedPosition;
		}
	}

	meshBounds = Box(glm::vec3(boundVertices[0].x, boundVertices[1].y, 0),glm::vec3(boundVertices[2].x, boundVertices[3].y, 0));

	for (int i = 0; i < 4; ++i)
	{
		glm::vec2 projectedPosition = boundVertices[i];
		glm::ivec2 scaledPosition = glm::ivec2(boundVertices[i] * accuracy);
		if (std::find(positions.begin(), positions.end(), scaledPosition) == positions.end())
		{
			positions.push_back(scaledPosition);
		}
		uniquePositions.push_back(projectedPosition);
		middlePoint += projectedPosition;
	}

	for (unsigned int vertexIndex = 0; vertexIndex < vertices.size(); ++vertexIndex)
	{
		glm::vec2 projectedPosition = projection * glm::vec3(transformation * glm::vec4(vertices[vertexIndex].m_position, 1));
		glm::ivec2 scaledPosition = glm::ivec2(projectedPosition * accuracy);
		if (std::find(positions.begin(), positions.end(), scaledPosition) == positions.end())
		{
			positions.push_back(scaledPosition);
			uniquePositions.push_back(projectedPosition);
			middlePoint += projectedPosition;
		}
	}

	middlePoint /= uniquePositions.size();
	std::sort(uniquePositions.begin(), uniquePositions.end(), [](const glm::vec2& a, const glm::vec2& b) { return a.x < b.x; });

	bool firstRun = true;
	while (nextPointIndex != startPointIndex || firstRun)
	{
		firstRun = false;
		unsigned int pI1 = nextPointIndex;
		glm::vec2 &p1(uniquePositions[pI1]);
		bool foundExtremePoint = false;
		for (unsigned int pI2 = 0; pI2 < uniquePositions.size() && !foundExtremePoint; ++pI2)
		{
			if (pI1 != pI2)
			{
				bool extremePoint = true;
				glm::vec2 &p2(uniquePositions[pI2]);
				for (unsigned int pI3 = 0; pI3 < uniquePositions.size() && extremePoint; ++pI3)
				{
					if (pI1 != pI3 && pI2 != pI3)
					{
						glm::vec2 &p3(uniquePositions[pI3]);
						float side = VecHelper::sideOfPoint(p1, p2, p3);
						if (side >= 0)
						{
							side = VecHelper::sideOfPoint(p1, p2, p3);
							extremePoint = false;
						}
					}
				}
				if (extremePoint)
				{
					convexHullPositions.push_back(pI2);
					nextPointIndex = pI2;
					foundExtremePoint = true;
				}
			}
		}
	}
	convexHullPositions.push_back(static_cast<int>(uniquePositions.size()));
	uniquePositions.push_back(middlePoint);


	std::vector<Vertex3DNormTex> meshVertices;
	std::vector<GLuint> indices;
	glm::vec3 invAxis1(axis1.x == 0 ? 0.0f : 1.0f / axis1.x, axis1.y == 0 ? 0.0f : 1.0f / axis1.y, axis1.z == 0 ? 0.0f : 1.0f / axis1.z);
	glm::vec3 invAxis2(axis2.x == 0 ? 0.0f : 1.0f / axis2.x, axis2.y == 0 ? 0.0f : 1.0f / axis2.y, axis2.z == 0 ? 0.0f : 1.0f / axis2.z);
	glm::mat2x3 projectionToWorld(invAxis1, invAxis2);
	glm::vec3 normal(-glm::cross(axis1, axis2));
	for (unsigned int convexHullPositionIndex = 0; convexHullPositionIndex < convexHullPositions.size(); ++convexHullPositionIndex)
	{
		glm::vec2 position = uniquePositions[convexHullPositions[convexHullPositionIndex]];

		Vertex3DNormTex vertex;
		vertex.m_position = projectionToWorld * position;
		vertex.m_texCoord = glm::vec2((static_cast<float>(position.x) - meshBounds.getX()) / meshBounds.getWidth(), (static_cast<float>(position.y) - meshBounds.getY()) / meshBounds.getHeight());
		vertex.m_normal = normal;
		meshVertices.push_back(vertex);

		if (convexHullPositionIndex < convexHullPositions.size() - 1)
		{
			indices.push_back(convexHullPositionIndex);
			indices.push_back((convexHullPositionIndex + 1) % (static_cast<int>(convexHullPositions.size()) - 1));
			indices.push_back(static_cast<int>(convexHullPositions.size()) - 1);
		}
	}

	mesh->addVertex(meshVertices);
	mesh->setIndices(indices);
	return mesh;
}