예제 #1
0
파일: Buffer.hpp 프로젝트: wibbe/slg
 void quad(T const& a, T const& b, T const& c, T const& d)
 {
   triangle(a, b, c);
   triangle(a, c, d);
 }
예제 #2
0
static void
four_tetras (GL_VECTOR *outer, Bool wireframe_p, int countdown)
{
  if (countdown <= 0)
    {
      triangle (outer[0].x, outer[0].y, outer[0].z,
                outer[1].x, outer[1].y, outer[1].z,
                outer[2].x, outer[2].y, outer[2].z,
                wireframe_p);
      triangle (outer[0].x, outer[0].y, outer[0].z,
                outer[3].x, outer[3].y, outer[3].z,
                outer[1].x, outer[1].y, outer[1].z,
                wireframe_p);
      triangle (outer[0].x, outer[0].y, outer[0].z,
                outer[2].x, outer[2].y, outer[2].z,
                outer[3].x, outer[3].y, outer[3].z,
                wireframe_p);
      triangle (outer[1].x, outer[1].y, outer[1].z,
                outer[3].x, outer[3].y, outer[3].z,
                outer[2].x, outer[2].y, outer[2].z,
                wireframe_p);
    }
  else
    {
#     define M01 0
#     define M02 1
#     define M03 2
#     define M12 3
#     define M13 4
#     define M23 5
      GL_VECTOR inner[M23+1];
      GL_VECTOR corner[4];

      inner[M01].x = (outer[0].x + outer[1].x) / 2.0;
      inner[M01].y = (outer[0].y + outer[1].y) / 2.0;
      inner[M01].z = (outer[0].z + outer[1].z) / 2.0;

      inner[M02].x = (outer[0].x + outer[2].x) / 2.0;
      inner[M02].y = (outer[0].y + outer[2].y) / 2.0;
      inner[M02].z = (outer[0].z + outer[2].z) / 2.0;

      inner[M03].x = (outer[0].x + outer[3].x) / 2.0;
      inner[M03].y = (outer[0].y + outer[3].y) / 2.0;
      inner[M03].z = (outer[0].z + outer[3].z) / 2.0;

      inner[M12].x = (outer[1].x + outer[2].x) / 2.0;
      inner[M12].y = (outer[1].y + outer[2].y) / 2.0;
      inner[M12].z = (outer[1].z + outer[2].z) / 2.0;

      inner[M13].x = (outer[1].x + outer[3].x) / 2.0;
      inner[M13].y = (outer[1].y + outer[3].y) / 2.0;
      inner[M13].z = (outer[1].z + outer[3].z) / 2.0;

      inner[M23].x = (outer[2].x + outer[3].x) / 2.0;
      inner[M23].y = (outer[2].y + outer[3].y) / 2.0;
      inner[M23].z = (outer[2].z + outer[3].z) / 2.0;

      countdown--;

      corner[0] = outer[0];
      corner[1] = inner[M01];
      corner[2] = inner[M02];
      corner[3] = inner[M03];
      four_tetras (corner, wireframe_p, countdown);

      corner[0] = inner[M01];
      corner[1] = outer[1];
      corner[2] = inner[M12];
      corner[3] = inner[M13];
      four_tetras (corner, wireframe_p, countdown);

      corner[0] = inner[M02];
      corner[1] = inner[M12];
      corner[2] = outer[2];
      corner[3] = inner[M23];
      four_tetras (corner, wireframe_p, countdown);

      corner[0] = inner[M03];
      corner[1] = inner[M13];
      corner[2] = inner[M23];
      corner[3] = outer[3];
      four_tetras (corner, wireframe_p, countdown);
    }
}
예제 #3
0
void Bitmap::DrawTriangle(const Triangle &tr, color_t color)
{
	triangle(_alBitmap,
		tr.X1, tr.Y1, tr.X2, tr.Y2, tr.X3, tr.Y3, color);
}
예제 #4
0
TArray<FVector> generate_triangles() {
	triangle(FVector(1000, 0, 0), FVector(0, 0, 0), FVector(500, 0, 1000));
	return triangle(FVector(500, 0, 0), FVector(0, 0, 0), FVector(500, 0, 1000));
}
예제 #5
0
cv::Mat projectWithEigen()
{
	// Transform meshes into camera frame

	// For each frame in vector
	for (int frame = 0; frame < mMeshFrameIDs.size(); frame++)
	{
		// Lookup current transform
		Eigen::Isometry3 transform;
		transform = transforms.at(mMeshFrameIDs[frame]);

		// Get copy of mesh for each frame
		ap::Mesh* sourceMesh;
		ap::Mesh* transformedMesh;
		//std::cerr << "Getting frame " << frame << " : " << mMeshFrameIDs[frame] << std::endl;
		MeshMap::iterator scene_i = scenes.find(mMeshFrameIDs[frame]);
		if (scenes.end() == scene_i) { continue; }
		sourceMesh = scene_i->second;

		MeshMap::iterator scene_t = transformedScenes.find(mMeshFrameIDs[frame]);
		if (transformedScenes.end() == scene_t) { continue; }
		transformedMesh = scene_t->second;

		// Transform mesh into camera frame
		for (int i = 0; i < sourceMesh->vertices.size(); i++)
		{
			Eigen::Vector3 newVertex = transform * sourceMesh->vertices[i];
			//std::cerr << mesh->vertices[i].transpose() << "\t->\t" << newVertex.transpose() << std::endl;
			transformedMesh->vertices[i] = newVertex;
		}
	}

	// For each pixel in camera image
	cv::Mat robotImage(mCameraModel.cameraInfo().height, mCameraModel.cameraInfo().width, CV_32F);
	float* pixelPtr = (float*)robotImage.data;
	float maxDepth = 0;
	for (int v = 0; v < robotImage.rows; v++)
	{
		for (int u = 0; u < robotImage.cols; u++)
		{
			// Create a ray through the pixel
			int pixelIdx = u + (v * robotImage.cols);
			//std::cerr << "Pixel (" << u << "," << v << ")" << std::endl;
			cv::Point2d pixel = cv::Point2d(u, v);
			cv::Point3d cvRay = mCameraModel.projectPixelTo3dRay(pixel);
			// Convert cvRay to ap::Ray
			ap::Ray ray;
			ray.point = Eigen::Vector3::Zero();
			ray.vector.x() = cvRay.x; ray.vector.y() = cvRay.y; ray.vector.z() = cvRay.z;
			ray.vector.normalize();
			//std::cerr << ray.vector.transpose() << std::endl;

			// For each frame in vector
			for (int frame = 0; frame < mMeshFrameIDs.size(); frame++)
			{
				MeshMap::iterator scene_i = transformedScenes.find(mMeshFrameIDs[frame]);
				if (transformedScenes.end() == scene_i)
				{
					continue;
				}
				ap::Mesh* mesh = scene_i->second;

				// For each triangle in mesh
				for (int i = 0; i < mesh->faces.size(); i++)
				{
					// Check for intersection. If finite, set distance

					ap::Triangle triangle(mesh->vertices[mesh->faces[i].vertices[0]],
										  mesh->vertices[mesh->faces[i].vertices[1]],
										  mesh->vertices[mesh->faces[i].vertices[2]]);

					Eigen::Vector3 intersection = ap::intersectRayTriangle(ray, triangle);
					if (std::isfinite(intersection.x()))
					{
						float d = intersection.norm();
						float val = pixelPtr[pixelIdx];
						if (val == 0 || val > d)
						{
							pixelPtr[pixelIdx] = d;
						}
						if (d > maxDepth)
						{
							maxDepth = d;
						}
					}
				}
			}
		}
	}

	// Return the matrix
	if (maxDepth == 0) { maxDepth = 1;}
	return robotImage/maxDepth;
}
예제 #6
0
  void BVH4mbBuilder::computePrimRefsTrianglesMB(const size_t threadID, const size_t numThreads) 
  {
    DBG(PING);
    const size_t numGroups = scene->size();
    const size_t startID = (threadID+0)*numPrimitives/numThreads;
    const size_t endID   = (threadID+1)*numPrimitives/numThreads;
    
    PrimRef *__restrict__ const prims     = this->prims;

    // === find first group containing startID ===
    unsigned int g=0, numSkipped = 0;
    for (; g<numGroups; g++) {       
      if (unlikely(scene->get(g) == NULL)) continue;
      if (unlikely(scene->get(g)->type != TRIANGLE_MESH)) continue;
      const TriangleMeshScene::TriangleMesh* __restrict__ const mesh = scene->getTriangleMesh(g);
      if (unlikely(!mesh->isEnabled())) continue;
      if (unlikely(mesh->numTimeSteps == 1)) continue;

      const size_t numTriangles = mesh->numTriangles;
      if (numSkipped + numTriangles > startID) break;
      numSkipped += numTriangles;
    }

    // === start with first group containing startID ===
    mic_f bounds_scene_min((float)pos_inf);
    mic_f bounds_scene_max((float)neg_inf);
    mic_f bounds_centroid_min((float)pos_inf);
    mic_f bounds_centroid_max((float)neg_inf);

    unsigned int num = 0;
    unsigned int currentID = startID;
    unsigned int offset = startID - numSkipped;

    __align(64) PrimRef local_prims[2];
    size_t numLocalPrims = 0;
    PrimRef *__restrict__ dest = &prims[currentID];

    for (; g<numGroups; g++) 
    {
      if (unlikely(scene->get(g) == NULL)) continue;
      if (unlikely(scene->get(g)->type != TRIANGLE_MESH)) continue;
      const TriangleMeshScene::TriangleMesh* __restrict__ const mesh = scene->getTriangleMesh(g);
      if (unlikely(!mesh->isEnabled())) continue;
      if (unlikely(mesh->numTimeSteps == 1)) continue;

      for (unsigned int i=offset; i<mesh->numTriangles && currentID < endID; i++, currentID++)	 
      { 			    
	//DBG_PRINT(currentID);
	const TriangleMeshScene::TriangleMesh::Triangle& tri = mesh->triangle(i);
	prefetch<PFHINT_L2>(&tri + L2_PREFETCH_ITEMS);
	prefetch<PFHINT_L1>(&tri + L1_PREFETCH_ITEMS);

	const float *__restrict__ const vptr0 = (float*)&mesh->vertex(tri.v[0]);
	const float *__restrict__ const vptr1 = (float*)&mesh->vertex(tri.v[1]);
	const float *__restrict__ const vptr2 = (float*)&mesh->vertex(tri.v[2]);

	const mic_f v0 = broadcast4to16f(vptr0);
	const mic_f v1 = broadcast4to16f(vptr1);
	const mic_f v2 = broadcast4to16f(vptr2);

	const mic_f bmin = min(min(v0,v1),v2);
	const mic_f bmax = max(max(v0,v1),v2);
	bounds_scene_min = min(bounds_scene_min,bmin);
	bounds_scene_max = max(bounds_scene_max,bmax);
	const mic_f centroid2 = bmin+bmax;
	bounds_centroid_min = min(bounds_centroid_min,centroid2);
	bounds_centroid_max = max(bounds_centroid_max,centroid2);

	store4f(&local_prims[numLocalPrims].lower,bmin);
	store4f(&local_prims[numLocalPrims].upper,bmax);	
	local_prims[numLocalPrims].lower.a = g;
	local_prims[numLocalPrims].upper.a = i;

	//DBG_PRINT( local_prims[numLocalPrims] );

	numLocalPrims++;
	if (unlikely(((size_t)dest % 64) != 0) && numLocalPrims == 1)
	  {
	    *dest = local_prims[0];
	    dest++;
	    numLocalPrims--;
	  }
	else
	  {
	    const mic_f twoAABBs = load16f(local_prims);
	    if (numLocalPrims == 2)
	      {
		numLocalPrims = 0;
		store16f_ngo(dest,twoAABBs);
		dest+=2;
	      }
	  }	
      }
      if (currentID == endID) break;
      offset = 0;
    }

    /* is there anything left in the local queue? */
    if (numLocalPrims % 2 != 0)
      *dest = local_prims[0];

    /* update global bounds */
    Centroid_Scene_AABB bounds;
    
    store4f(&bounds.centroid2.lower,bounds_centroid_min);
    store4f(&bounds.centroid2.upper,bounds_centroid_max);
    store4f(&bounds.geometry.lower,bounds_scene_min);
    store4f(&bounds.geometry.upper,bounds_scene_max);

    global_bounds.extend_atomic(bounds);    
  }
예제 #7
0
파일: bitmap.cpp 프로젝트: prylee/Bitmap
void Bitmap::p4(P2 p1, P2 p2, P2 p3, P2 p4) {
    triangle(p1, p2, p3);
    triangle(p1, p2, p4);
}
예제 #8
0
static void display(void) {
    glClear(GL_COLOR_BUFFER_BIT);
    glEnable (GL_LINE_SMOOTH);
    glEnable (GL_BLEND);
    glEnable (GL_POLYGON_SMOOTH);
    glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    glHint (GL_LINE_SMOOTH_HINT, GL_NICEST);

    
    glColor3f(0.6,0.3,0.0);
    rectangle(GL_QUADS);

    glColor3f(1.0,1.0,1.0);
    glEnable(GL_LINE_STIPPLE);
    glLineStipple(1, 0xF0F0);
    glLineWidth(3.0f);
    glBegin(GL_LINE_LOOP);
        glVertex2f(-1,-0.7);
        glVertex2f(1,-0.7);
        glVertex2f(1,-0.1);
        glVertex2f(-1,-0.1);
    glEnd();

    glColor3f(1.0,1.0,1.0);
    glPushMatrix();
        glTranslatef(-.65,-.15,0);
        glColor3f(0.2,1.0,.2);
        triangle();
    glPopMatrix();

    glPushMatrix();
        glTranslatef(-.65,.95,0);
        glColor3f(0.0,0.0,0.0);
        triangle(); 
    glPopMatrix();

    glPushMatrix();
        glColor3f(0.0,0.0,0.0);
        glTranslatef(0.0,.78,0.0);
        drawCircle(0.18f);
    glPopMatrix();

    glPushMatrix();
        glColor3f(1.0,0.0,0.0);
        glTranslatef(0.0,-0.3,0.0);
        drawCircle(0.18f);
    glPopMatrix();

    glPushMatrix();
    glTranslatef(0.0,-0.05,0.0);
    glScalef(0.08,0.007,0.08);
    //glPointSize(0.5f);
    glBegin(GL_POINTS);
    for (float i=-19.0f; i < 109.5f; i += .5f) {
        glColor3f(0,i*.1,i*-.1);
        glVertex2f(i,sin(i)*3);
    }
    glEnd();
    glPopMatrix();

    glPushMatrix();
    char* string = "Brian Gianforcaro - RIT 2008/2009";
    int len = (int) strlen(string);
    glColor3f(1.0,1.0,1.0);
    glRasterPos2f(-0.4,1.05);
    for (int i = 0; i < len; i++) {
        glutBitmapCharacter(GLUT_BITMAP_TIMES_ROMAN_10, string[i]);
    }
    glPopMatrix();

    glPushMatrix();
    glTranslatef(0.45,-.54,0);
        glEnable(GL_POLYGON_STIPPLE);
        glPolygonStipple(stippleBits);
        glBegin(GL_POLYGON);
            glColor3f(1.0,0,0);
            glVertex2f(0,0);
            glColor3f(0,1.0,0);
            glVertex2f(.4,0);
            glColor3f(0,0,1.0);
            glVertex2f(.4,.4);
            glColor3f(1.0,1.0,1.0);
            glVertex2f(0,.4);
        glEnd();
    glPopMatrix();
    glDisable(GL_POLYGON_STIPPLE);

    glColor3f(0,0,0);
    glPushMatrix();
        glTranslatef(0.45,.56,0);
        glBegin(GL_POLYGON);
            glVertex2f(0,0);
            glVertex2f(.4,0);
            glVertex2f(.4,.4);
            glVertex2f(0,.4);
        glEnd();
    glPopMatrix();


    glColor3f(1,1,1);
    glDisable(GL_LINE_STIPPLE);
    glPushMatrix();
    glTranslatef(-1,-1.1,0);
        glBegin(GL_LINES);
        for (float i = 0; i < 2.1; i+=.1f) {
            glVertex2f(i, 0);
            glVertex2f(i, .3);
        }
        for (float i = 0; i < .35; i+=.05f) {
            glVertex2f(0, i);
            glVertex2f(2, i);
        }
        glEnd();
    glPopMatrix();


    glFlush();
}
예제 #9
0
  void 
  RTriangleMesh::init(const std::tr1::shared_ptr<magnet::thread::TaskQueue>& systemQueue)
  {
    RTriangles::init(systemQueue);

    //Send the data we already have
    setGLPositions(_vertices);
    setGLElements(_elements);

    {//Calculate the normal vectors
      std::vector<float> VertexNormals(_vertices.size(), 0);
    
      //For every triangle, add the cross product of the two edges. We
      //then renormalize the normal to get a
      //"weighted-by-the-triangle-size" normal.
    
      for (size_t triangle(0); triangle < _elements.size() / 3; ++triangle)
	{
	  //Grab the vertex IDs
	  size_t v1(_elements[3 * triangle + 0]),
	    v2(_elements[3 * triangle + 1]),
	    v3(_elements[3 * triangle + 2]);
	
	  Vector V1(_vertices[3 * v1 + 0],
		    _vertices[3 * v1 + 1],
		    _vertices[3 * v1 + 2]),
	    V2(_vertices[3 * v2 + 0],
	       _vertices[3 * v2 + 1],
	       _vertices[3 * v2 + 2]),
	    V3(_vertices[3 * v3 + 0],
	       _vertices[3 * v3 + 1],
	       _vertices[3 * v3 + 2]);

	  Vector norm = (V2-V1)^(V3-V2);
	
	  for (size_t i(0); i < 3; ++i)
	    {
	      VertexNormals[3 * v1 + i] += norm[i];
	      VertexNormals[3 * v2 + i] += norm[i];
	      VertexNormals[3 * v3 + i] += norm[i];
	    }
	}

      //Now normalize those vertices
      for (size_t vert(0); vert < _vertices.size() / 3; ++vert)
	{
	  double norm 
	    = VertexNormals[3 * vert + 0] * VertexNormals[3 * vert + 0]
	    + VertexNormals[3 * vert + 1] * VertexNormals[3 * vert + 1]
	    + VertexNormals[3 * vert + 2] * VertexNormals[3 * vert + 2];
	
	  if (norm)
	    {
	      double factor = 1 / std::sqrt(norm);
	      VertexNormals[3 * vert + 0] *= factor;
	      VertexNormals[3 * vert + 1] *= factor;
	      VertexNormals[3 * vert + 2] *= factor;
	    }
	  else
	    {
	      VertexNormals[3 * vert + 0] = 1;
	      VertexNormals[3 * vert + 1] = 0;
	      VertexNormals[3 * vert + 2] = 0;
	    }
	}

      setGLNormals(VertexNormals);
    }
  
    //Reclaim some memory
    _vertices.clear();
    _elements.clear();
  }
예제 #10
0
//----------------------------------------------------------
void ofPath::triangle(const ofPoint & p1, const ofPoint & p2, const ofPoint & p3){
	triangle(p1.x,p1.y,p1.z,p2.x,p2.y,p2.z,p3.x,p3.y,p3.z);
}
예제 #11
0
bool TriangleMesherInterface :: meshPSLG(const Triangle_PSLG &pslg,
                                         const IntArray &outside, const IntArray &inside,
                                         std :: vector< FloatArray > &nodes, std :: vector< IntArray > &n_markers,
                                         std :: vector< IntArray > &triangles, IntArray &t_markers,
                                         std :: vector< IntArray > &segments, IntArray &s_markers) const
{
#ifdef __TRIANGLE_MODULE
    // 1. Fill the struct for triangle;
    struct triangulateio mesh;
    clearTriangulateIO(mesh);

    // 1.a. Copy over the node data.
    mesh.numberofpoints = pslg.nx.giveSize();
    mesh.pointlist = new REAL [ mesh.numberofpoints * 2 ];
    //mesh.pointmarkerlist = new REAL[mesh.numberofpoints];
    for ( int i = 0; i < mesh.numberofpoints; ++i ) {
        mesh.pointlist [ i * 2 ] = pslg.nx(i);
        mesh.pointlist [ i * 2 + 1 ] = pslg.ny(i);
        //mesh.pointmarkerlist[i] = pslg.n_marker(i);
    }

    // 1.b. Copy over the segment data
    printf("Copying segment data\n");
    mesh.numberofsegments = pslg.segment_a.giveSize();
    mesh.segmentlist = new int [ mesh.numberofsegments * 2 ];
    for ( int i = 0; i < mesh.numberofsegments; ++i ) {
        mesh.segmentlist [ i * 2 ] = pslg.segment_a(i);
        mesh.segmentlist [ i * 2 + 1 ] = pslg.segment_b(i);
    }

    if ( pslg.segment_marker.giveSize() > 0 ) {
        mesh.segmentmarkerlist = new int [ mesh.numberofsegments ];
        for ( int i = 0; i < mesh.numberofsegments; ++i ) {
            mesh.segmentmarkerlist [ i ] = pslg.segment_marker(i);
        }
    }

    // 2. Triangulate
    char options [ 100 ];
    // Note: Not sure if -A is necessary when using the library interface.
    sprintf(options, "-p -q %f -a%f %s -A", this->minAngle, this->maxArea, this->quadratic ? "-o2" : "");
    struct triangulateio output;
    clearTriangulateIO(output);
    custom_triangulate( options, & mesh, & output, NULL, outside.givePointer(), inside.givePointer() );

    // 3. Copy back
    nodes.resize(output.numberofpoints);
    //n_markers.resize(output.numberofpoints);
    for ( int i = 0; i < output.numberofpoints; ++i ) {
        nodes [ i ].resize(2);
        nodes [ i ].at(1) = output.pointlist [ i * 2 ];
        nodes [ i ].at(2) = output.pointlist [ i * 2 + 1 ];
        //n_markers(i) = output.pointmarkerlist[i]; // Not enough.
    }

    triangles.resize(output.numberoftriangles);
    t_markers.resize(output.numberoftriangles);
    for ( int i = 0; i < output.numberoftriangles; ++i ) {
        IntArray &triangle = triangles [ i ];
        triangle.resize(output.numberofcorners);
        for ( int j = 0; j < 3; j++ ) { // First three
            triangle(j) = output.trianglelist [ i * output.numberofcorners + j ];
        }
        // Rearrange the strange ordering of the edge nodes.
        if ( output.numberofcorners == 6 ) {
            triangle(3) = output.trianglelist [ i * output.numberofcorners + 5 ];
            triangle(4) = output.trianglelist [ i * output.numberofcorners + 3 ];
            triangle(5) = output.trianglelist [ i * output.numberofcorners + 4 ];
        }
        t_markers.at(i + 1) = ( int ) round(output.triangleattributelist [ i ]);
    }

    // A somewhat annoying missing feature of triangle, it won't make the segments quadratic.
    std :: set< std :: size_t > *node_triangle = NULL;
    if ( this->quadratic ) {
        node_triangle = new std :: set< std :: size_t > [ output.numberofpoints ];
        for ( std :: size_t i = 0; i < triangles.size(); ++i ) {
            IntArray &triangle = triangles [ i ];
            for ( int j = 1; j <= 3; ++j ) {
                node_triangle [ triangle.at(j) - 1 ].insert(i);
            }
        }
    }

    segments.resize(output.numberofsegments);
    s_markers.resize(output.numberofsegments);
    for ( int i = 0; i < output.numberofsegments; ++i ) {
        IntArray &segment = segments [ i ];
        segment.resize(this->quadratic ? 3 : 2);
        segment.at(1) = output.segmentlist [ i * 2 + 0 ];
        segment.at(2) = output.segmentlist [ i * 2 + 1 ];
        //segment->at(3) = output.segmentlist[i*3 + 2]; // Quadratic meshes only, not for segments.
        if ( this->quadratic ) {
            int a, b, c;
            std :: set< std :: size_t >tris = node_triangle [ segment.at(1) - 1 ];
            // Now look up any triangle with the other point included.
            for ( auto tri: tris ) {
                IntArray &triangle = triangles [ tri ];
                if ( ( b = triangle.findFirstIndexOf( segment.at(2) ) ) > 0 ) {
                    a = triangle.findFirstIndexOf( segment.at(1) );
                    if ( a + b == 3 ) {
                        c = 4;
                    } else if ( a + b == 5 ) {
                        c = 5;
                    } else {
                        c = 6;
                    }
                    segment.at(3) = triangle.at(c);
                    break;
                }
            }
        }
        s_markers.at(i + 1) = output.segmentmarkerlist [ i ];
    }
    if ( this->quadratic ) {
        delete[] node_triangle;
    }

    this->fixNodeMarkers(nodes, n_markers, triangles, t_markers, segments, s_markers);

    // Deleting old memory
    delete[] mesh.pointlist;
    //delete[] mesh.pointattributelist;
    //delete[] mesh.pointmarkerlist;
    //delete[] mesh.trianglelist;
    //delete[] mesh.triangleattributelist;
    //delete[] mesh.trianglearealist;
    delete[] mesh.segmentlist;
    delete[] mesh.segmentmarkerlist;
    //if (mesh.holelist) { delete[] mesh.holelist; }
    //if (mesh.regionlist) { delete[] mesh.regionlist; }

    // Holes and regions are referenced in both.
    free(output.pointlist);
    //free(output.pointattributelist);
    free(output.pointmarkerlist);
    free(output.trianglelist);
    free(output.triangleattributelist);
    //free(output.trianglearealist);
    free(output.segmentlist);
    free(output.segmentmarkerlist);
    //free(output.holelist);
    //free(output.regionlist);
#else
    OOFEM_ERROR("OOFEM is not compiled with support for triangle.");
#endif

    return true;
}
예제 #12
0
//----------------------------------------------------------
void ofPath::triangle(float x1,float y1,float x2,float y2,float x3, float y3){
	triangle(x1,y1,0.0f,x2,y2,0.0f,x3,y3,0.0f);
}
예제 #13
0
static void
draw_triangles (ModeInfo *mi, GLfloat fold_ratio, GLfloat stel_ratio)
{
  planetstruct *gp = &planets[MI_SCREEN(mi)];
  Bool wire = MI_IS_WIREFRAME(mi);
  GLfloat h = sqrt(3) / 2;
  GLfloat c = h / 3;

  glTranslatef (0, -h/3, 0);  /* Center on face 12 */

  /* When closed, center on midpoint of icosahedron. Eyeballed this. */
  glTranslatef (0, 0, fold_ratio * 0.754);

  glFrontFace (GL_CCW);

  /* Adjust the texture matrix so that it has the same coordinate space
     as the model. */

  glMatrixMode(GL_TEXTURE);
  glPushMatrix();
  {
    GLfloat texw = 5.5;
    GLfloat texh = 3 * h;
    GLfloat midx = 2.5;
    GLfloat midy = 3 * c;
    glScalef (1/texw, -1/texh, 1);
    glTranslatef (midx, midy, 0);
  }
  glMatrixMode(GL_MODELVIEW);



  /* Front faces */

  if (wire)
    glDisable (GL_TEXTURE_2D);
  else if (do_texture)
    {
      glEnable (GL_TEXTURE_2D);
      glBindTexture (GL_TEXTURE_2D, gp->tex1);
    }
  else
    glDisable (GL_TEXTURE_2D);

  triangle (mi, 12, True, fold_ratio, stel_ratio);

  /* Back faces */

  if (wire)
    glDisable (GL_TEXTURE_2D);
  else if (do_texture)
    {
      glEnable (GL_TEXTURE_2D);
      glBindTexture (GL_TEXTURE_2D, gp->tex2);
    }
  else
    glDisable (GL_TEXTURE_2D);

  glFrontFace (GL_CW);

  triangle (mi, 12, False, fold_ratio, 0);

  glMatrixMode(GL_TEXTURE);
  glPopMatrix();
  glMatrixMode(GL_MODELVIEW);
}
예제 #14
0
/* The segments, numbered arbitrarily from the top left:
             ________         _      ________
             \      /\      /\ \    |\      /
              \ 0  /  \    /  \3>   | \ 5  /
               \  / 1  \  / 2  \| ..|4 \  /-6-..
     ___________\/______\/______\/______\/______\
    |   /\      /\      /\      /\      /\   
    |7 /  \ 9  /  \ 11 /  \ 13 /  \ 15 /  \  
    | / 8  \  / 10 \  / 12 \  / 14 \  / 16 \ 
    |/______\/______\/______\/______\/______\
     \      /\      /       /\      /\
      \ 17 /  \ 18 /       /  \ 20 /  \
       \  /    \  /       / 19 \  / 21 \
        \/      \/       /______\/______\

   Each triangle can be connected to at most two other triangles.
   We start from the middle, #12, and work our way to the edges.
   Its centroid is 0,0.
 */
static void
triangle (ModeInfo *mi, int which, Bool frontp, 
          GLfloat fold_ratio, GLfloat stel_ratio)
{
  planetstruct *gp = &planets[MI_SCREEN(mi)];
  const GLfloat fg[3] = { 1, 1, 1 };
  const GLfloat bg[3] = { 0.3, 0.3, 0.3 };
  int a = -1, b = -1;
  GLfloat max = acos (sqrt(5)/3);
  GLfloat rot = -max * fold_ratio / (M_PI/180);
  Bool wire = MI_IS_WIREFRAME(mi);

  if (wire)
    glColor3fv (fg);

  switch (which) {
  case 3:				/* One third of the face. */
    triangle0 (mi, frontp, stel_ratio, 1<<3 | 1<<4);
    break;
  case 4:				/* Two thirds of the face: convex. */
    triangle0 (mi, frontp, stel_ratio, 1<<1 | 1<<2 | 1<<3 | 1<<4);
    break;
  case 6:				/* One half of the face. */
    triangle0 (mi, frontp, stel_ratio, 1<<1 | 1<<2 | 1<<3);
    break;
  case 7:				/* One half of the face. */
    triangle0 (mi, frontp, stel_ratio, 1<<2 | 1<<3 | 1<<4);
    break;
  default:				/* Full face. */
    triangle0 (mi, frontp, stel_ratio, 0x3F);
    break;
  }

  if (wire)
    {
      char tag[20];
      glColor3fv (bg);
      sprintf (tag, "%d", which);
      glPushMatrix();
      glTranslatef (-0.1, 0.2, 0);
      glScalef (0.005, 0.005, 0.005);
      print_texture_string (gp->font_data, tag);
      glPopMatrix();
      mi->polygon_count++;
    }


  /* The connection hierarchy of the faces starting at the middle, #12. */
  switch (which) {
  case  0: break;
  case  1: a =  0; b = -1; break;
  case  2: a = -1; b =  3; break;
  case  3: break;
  case  4: a = -1; b =  5; break;
  case  5: a = -1; b =  6; break;
  case  7: break;
  case  6: break;
  case  8: a = 17; b =  7; break;
  case  9: a =  8; b = -1; break;
  case 10: a = 18; b =  9; break;
  case 11: a = 10; b =  1; break;
  case 12: a = 11; b = 13; break;
  case 13: a =  2; b = 14; break;
  case 14: a = 15; b = 20; break;
  case 15: a =  4; b = 16; break;
  case 16: break;
  case 17: break;
  case 18: break;
  case 19: break;
  case 20: a = 21; b = 19; break;
  case 21: break;
  default: abort(); break;
  }

  if (a != -1)
    {
      glPushMatrix();
      glTranslatef (-0.5, 0, 0);	/* Move model matrix to upper left */
      glRotatef (60, 0, 0, 1);
      glTranslatef ( 0.5, 0, 0);

      glMatrixMode(GL_TEXTURE);
      /* glPushMatrix(); */
      glTranslatef (-0.5, 0, 0);	/* Move texture matrix the same way */
      glRotatef (60, 0, 0, 1);
      glTranslatef ( 0.5, 0, 0);

      glMatrixMode(GL_MODELVIEW);

      glRotatef (rot, 1, 0, 0);
      triangle (mi, a, frontp, fold_ratio, stel_ratio);

      /* This should just be a PopMatrix on the TEXTURE stack, but
         f*****g iOS has GL_MAX_TEXTURE_STACK_DEPTH == 4!  WTF!
         So we have to undo our rotations and translations manually.
       */
      glMatrixMode(GL_TEXTURE);
      /* glPopMatrix(); */
      glTranslatef (-0.5, 0, 0);
      glRotatef (-60, 0, 0, 1);
      glTranslatef (0.5, 0, 0);

      glMatrixMode(GL_MODELVIEW);
      glPopMatrix();
    }

  if (b != -1)
    {
      glPushMatrix();
      glTranslatef (0.5, 0, 0);		/* Move model matrix to upper right */
      glRotatef (-60, 0, 0, 1);
      glTranslatef (-0.5, 0, 0);

      glMatrixMode(GL_TEXTURE);
      /* glPushMatrix(); */
      glTranslatef (0.5, 0, 0);		/* Move texture matrix the same way */
      glRotatef (-60, 0, 0, 1);
      glTranslatef (-0.5, 0, 0);

      glMatrixMode(GL_MODELVIEW);

      glRotatef (rot, 1, 0, 0);
      triangle (mi, b, frontp, fold_ratio, stel_ratio);

      /* See above. Grr. */
      glMatrixMode(GL_TEXTURE);
      /* glPopMatrix(); */
      glTranslatef (0.5, 0, 0);
      glRotatef (60, 0, 0, 1);
      glTranslatef (-0.5, 0, 0);

      glMatrixMode(GL_MODELVIEW);
      glPopMatrix();
    }
}
예제 #15
0
/**
 * \ingroup Main
 *
 * \brief Desenha uma rede no Allegro e imprime num arquivo de imagem.
 *
 * \details Esta funcao utiliza a biblioteca grafica Allegro para imprimir uma rede de Petri. 
 *
 * \param[in] rede A variavel \a rede seria a rede de Petri.
 *
 * \param[in] fname A variavel \a fname representa o nome do arquivo que sera gerado.
 *
 * \retval void a funcao retorna nada.
 *
 */
void desenha_rede(petri_t *rede, const char *fname)
{
    float ang,      /* Angulacao antre cada elemento na imagem */
          r_lugar,  /* Raio da circunferencia que representa o lugar */
          smaller,  /* A menor das dimensoes da imagem */
          x,        /* Variavel geral para representar coordenada X */
          y,        /* Variavel geral para representar coordenada Y */
          x1,       /* Variavel geral para representar coordenada X */
          y1,       /* Variavel geral para representar coordenada Y */
          x2,       /* Variavel geral para representar coordenada X */
          y2,       /* Variavel geral para representar coordenada Y */
          x3,       /* Variavel geral para representar coordenada X */
          y3,       /* Variavel geral para representar coordenada Y */
          co,       /* Variavel geral para representar cosseno */
          si;       /* Variavel geral para representar seno */

    unsigned i, q;
    lugar *a_l = rede->l;
    BITMAP *buff;
    PALETTE pal;
    flecha *a_tl = rede->tl,
           *a_lt = rede->lt;
    /* Inicializacao Allegro */
    if(install_allegro(SYSTEM_NONE, &errno, atexit)!=0)
        exit(EXIT_FAILURE);
    set_color_depth(16);
    get_palette(pal);
    buff = create_bitmap(IMG_X,IMG_Y);
    smaller = (float)IMG_X;
    if(smaller > (float)IMG_Y)
        smaller = (float)IMG_Y;
    r_lugar = smaller/4.0*(M_PI/(M_PI+(float)rede->total_l));
    if(buff == NULL)
    {
        printf("Could not create buffer!\n");
        exit(EXIT_FAILURE);
    }
    /* Desenho propriamente dito */

    if(rede->total_l > rede->total_t)
        ang = M_PI/rede->total_l;
    else
        ang = M_PI/rede->total_t;
    if(DEBUG == B || DEBUG == D) printf("Desenhando %u lugares e %u transicoes espacados entre si %.2fº...\n", rede->total_l, rede->total_t, ang*180.0/M_PI);

    /* Desenhando os lugares  */
    for(i=0;i<rede->total_l;i++)
    {
        a_l = buscarLugarPos(rede->l, i);
        q = 0;
        if(a_l != NULL)
            q = a_l->qtd;
        x = IMG_X/2.0 + (IMG_X/2.0 - r_lugar)*cos(2*i*ang);
        y = IMG_Y/2.0 + (IMG_Y/2.0 - r_lugar)*sin(2*i*ang);
        circle(buff, x, y, r_lugar, CORBRANCO);
        textprintf_ex(buff, font, x, y, CORVERDE, CORPRETO, "%u", q);
        if(DEBUG == B || DEBUG == D) printf("L%u(%u) (posicionada %.2fº)\n", i, q, ang*(2*i)*180.0/M_PI);
        textprintf_ex(buff, font, x, y - r_lugar, CORVERDE, CORPRETO, "L%u", i);
    }

    /* Desenhando as transicoes  */
    for(i=0;i<rede->total_t;i++)
    {
        x = IMG_X/2.0 + (IMG_X/2.0 - r_lugar)*cos((2*i+1)*ang);
        y = IMG_Y/2.0 + (IMG_Y/2.0 - r_lugar)*sin((2*i+1)*ang);
        line(buff, x, y+r_lugar, x, y-r_lugar, CORBRANCO);
        if(DEBUG == B || DEBUG == D) printf("T%u (posicionado %.2fº)\n", i, ang*(2*i+1)*180.0/M_PI);
        textprintf_ex(buff, font, x, y - r_lugar, CORVERDE, CORPRETO, "T%u", i);
    }

    /* Desenhando as flechas */
    while(a_tl != NULL)
    {
        i = a_tl->de;
        x1 = IMG_X/2.0 + (IMG_X/2.0 - r_lugar)*cos((2*i+1)*ang);
        y1 = IMG_Y/2.0 + (IMG_Y/2.0 - r_lugar)*sin((2*i+1)*ang);
        i = a_tl->para;
        x = IMG_X/2.0 + (IMG_X/2.0 - r_lugar)*cos(2*i*ang);
        y = IMG_Y/2.0 + (IMG_Y/2.0 - r_lugar)*sin(2*i*ang);
        co = lcos(x1,y1,x,y);
        si = lsin(x1,y1,x,y);
        x -= r_lugar*co;
        y -= r_lugar*si;
        line(buff, x1, y1, x, y, CORBRANCO);
        textprintf_ex(buff, font, (x+x1)/2, (y+y1)/2, CORVERDE, CORPRETO, "%u", a_tl->tk);
        x2 = x - (r_lugar / 4) * (si + co);
        y2 = y + (r_lugar / 4) * (co - si);
        x3 = x + (r_lugar / 4) * (si - co);
        y3 = y - (r_lugar / 4) * (si + co);
        triangle(buff, x, y, x2, y2, x3, y3, CORBRANCO);
        a_tl = a_tl->prox;
    }
    while(a_lt != NULL)
    {
        i = a_lt->de;
        x1 = IMG_X/2.0 + (IMG_X/2.0 - r_lugar)*cos(2*i*ang);
        y1 = IMG_Y/2.0 + (IMG_Y/2.0 - r_lugar)*sin(2*i*ang);
        i = a_lt->para;
        x = IMG_X/2.0 + (IMG_X/2.0 - r_lugar)*cos((2*i+1)*ang);
        y = IMG_Y/2.0 + (IMG_Y/2.0 - r_lugar)*sin((2*i+1)*ang);
        co = lcos(x1,y1,x,y);
        si = lsin(x1,y1,x,y);
        x1 += r_lugar*co;
        y1 += r_lugar*si;
        line(buff, x1, y1, x, y, CORBRANCO);
        textprintf_ex(buff, font, (x+x1)/2, (y+y1)/2, CORVERDE, CORPRETO, "%u", a_lt->tk);
        x2 = x - (r_lugar / 4) * (si + co);
        y2 = y + (r_lugar / 4) * (co - si);
        x3 = x + (r_lugar / 4) * (si - co);
        y3 = y - (r_lugar / 4) * (si + co);
        triangle(buff, x, y, x2, y2, x3, y3, CORBRANCO);
        a_lt = a_lt->prox;
    }
    /* Salvando Imagem */
    save_bitmap(fname, buff, pal);
    destroy_bitmap(buff);
    allegro_exit();
    if(!GIF) printf("Imagem %s salva com sucesso!\n", fname);
    return;
}
예제 #16
0
void
convert(		/* convert a T-mesh */
	char	*fname,
	FILE	*fp
)
{
	char	typ[4];
	int	id[3];
	double	vec[3];
	char	picfile[128];
	char	matname[64];
	char	objname[64];
	int	i;
	VERTEX	*lastv;
					/* start fresh */
	i = nverts;
	lastv = vlist;
	while (i--)
		(lastv++)->flags = 0;
	lastv = NULL;
	strcpy(picfile, defpat);
	strcpy(matname, defmat);
	strcpy(objname, defobj);

	printf("\n## T-mesh read from: %s\n", fname);
					/* scan until EOF */
	while (fscanf(fp, "%1s", typ) == 1)
		switch (typ[0]) {
		case 'v':		/* vertex */
			if (fscanf(fp, "%d %lf %lf %lf", &id[0],
					&vec[0], &vec[1], &vec[2]) != 4)
				syntax(fname, fp, "Bad vertex");
			lastv = vnew(id[0], vec[0], vec[1], vec[2]);
			break;
		case 't':		/* triangle */
			if (fscanf(fp, "%d %d %d", &id[0], &id[1], &id[2]) != 3)
				syntax(fname, fp, "Bad triangle");
			if (novert(id[0]) | novert(id[1]) | novert(id[2]))
				syntax(fname, fp, "Undefined triangle vertex");
			triangle(picfile, matname, objname, &vlist[id[0]],
					&vlist[id[1]], &vlist[id[2]]);
			break;
		case 'n':		/* surface normal */
			if (lastv == NULL)
				syntax(fname, fp, "No vertex for normal");
			if (fscanf(fp, "%lf %lf %lf",
					&vec[0], &vec[1], &vec[2]) != 3)
				syntax(fname, fp, "Bad vertex normal");
			lastv->nor[0] = vec[0];
			lastv->nor[1] = vec[1];
			lastv->nor[2] = vec[2];
			if (normalize(lastv->nor) == 0.0)
				syntax(fname, fp, "Zero vertex normal");
			lastv->flags |= V_HASNORM;
			break;
		case 'i':		/* index position */
			if (lastv == NULL)
				syntax(fname, fp, "No vertex for index");
			if (fscanf(fp, "%lf %lf", &vec[0], &vec[1]) != 2)
				syntax(fname, fp, "Bad index");
			lastv->ndx[0] = vec[0];
			lastv->ndx[1] = vec[1];
			lastv->flags |= V_HASINDX;
			break;
		case 'o':		/* object name */
			if (fscanf(fp, "%s", objname) != 1)
				syntax(fname, fp, "Bad object name");
			break;
		case 'm':		/* material */
			if (fscanf(fp, "%s", matname) != 1)
				syntax(fname, fp, "Bad material");
			if (matname[0] == '-' && !matname[1])
				strcpy(matname, VOIDID);
			break;
		case 'p':		/* picture */
			if (fscanf(fp, "%s", picfile) != 1)
				syntax(fname, fp, "Bad pattern");
			if (picfile[0] == '-' && !picfile[1])
				picfile[0] = '\0';
			break;
		case '#':		/* comment */
			fputs("\n#", stdout);
			while ((i = getc(fp)) != EOF) {
				putchar(i);
				if (i == '\n')
					break;
			}
			break;
		default:
			syntax(fname, fp, "Unknown type");
			break;
		}
}
예제 #17
0
int main(void)
     {
        double sideA, sideB, sideC, anga, angb, tempC;
        double pi = fabs(acos(-1.));
        double torads = pi/180.;
        double todegs = 180./pi;
        double angc = 90.;

        printf("Using the following conventions for sides and angles:\n");
        triangle();
        printf("\nEnter all known information:\n");
        printf("\tA = ");
        scanf("%lf", &sideA);
        printf("\tB = ");
        scanf("%lf", &sideB);
        printf("\tC = ");
        scanf("%lf", &sideC);
        printf("\tAngle a = ");
        scanf("%lf", &anga);
        printf("\tAngle b = ");
        scanf("%lf", &angb);
        if(sideA && sideB && sideC) {
             tempC = sqrt(pow(sideA, 2.) + pow(sideB, 2.));
             if(fabs(sideC - tempC) > 0.001) {
                  printf("Sides invalid.\n");
                  return(1);
             }
             anga = acos(sideB/sideC) * todegs;
             angb = 90. - anga;
        } else if(sideA && sideB) {
             sideC = sqrt(pow(sideA, 2.) + pow(sideB, 2.));
             anga = acos(sideB/sideC) * todegs;
             angb = 90. - anga;
        } else if(sideB && sideC) {
             sideA = sqrt(pow(sideC, 2.) - pow(sideB, 2.));
             anga = acos(sideB/sideC) * todegs;
             angb = 90. - anga;
        } else if(sideA && sideC) {
             sideB = sqrt(pow(sideC, 2.) - pow(sideA, 2.));
             anga = acos(sideB/sideC) * todegs;
             angb = 90. - anga;
        } else if(sideA) {
             if(anga && angb) {
                  sideC = sideA/cos(angb*torads);
                  sideB = sqrt(pow(sideC, 2.) - pow(sideA, 2.));
             } else if(anga) {
                  sideC = sideA/sin(anga*torads);
                  sideB = sqrt(pow(sideC, 2.) - pow(sideA, 2.));
                  angb = 90. - anga;
             } else if(angb) {
                  sideC = sideA/cos(angb*torads);
                  sideB = sqrt(pow(sideC, 2.) - pow(sideA, 2.));
                  anga = 90. - angb;
             } else {
                  printf("Insufficient information.\n");
                  return(1);
             }
        } else if(sideB) {
             if(anga && angb) {
                  sideC = sideB/sin(angb*torads);
                  sideA = sqrt(pow(sideC, 2.) - pow(sideB, 2.));
             } else if(anga) {
                  sideC = sideB/cos(anga*torads);
                  sideA = sqrt(pow(sideC, 2.) - pow(sideB, 2.));
                  angb = 90. - anga;
             } else if(angb) {
                  sideC = sideB/sin(angb*torads);
                  sideA = sqrt(pow(sideC, 2.) - pow(sideB, 2.));
                  anga = 90. - angb;
             } else {
                  printf("Insufficient information.\n");
                  return(1);
             }
        } else if(sideC) {
             if(anga && angb) {
                  sideA = sideC * cos(angb*torads);
                  sideB = sideC * sin(angb*torads);
             } else if(anga) {
                  sideA = sideC * sin(anga*torads);
                  sideB = sideC * cos(anga*torads);
                  angb = 90. - anga;
             } else if(angb) {
                  sideA = sideC * cos(angb*torads);
                  sideB = sideC * sin(angb*torads);
                  anga = 90. - angb;
             } else {
                  printf("Insufficient information.\n");
                  return(1);
             }
        } else {
             printf("Insufficient information.\n");
             return(1);
        }

        printf("\n\tSide A = %.2f\t\tAngle a = %.2f degrees\n", sideA, anga);
        printf("\tSide B = %.2f\t\tAngle b = %.2f degrees\n", sideB, angb);
        printf("\tSide C = %.2f\n", sideC);
     }
예제 #18
0
//! checks if there is collision
void Player::CheckCollision(const shoot::Vector3D& vPosition, const shoot::Vector3D& vVelocity,
							shoot::Vector3D& vNewPosition, shoot::Vector3D& vNewVelocity)
{
	shoot::Vertex3D* pVertices = m_pEnvironment->GetMesh()->GetVertexBuffer()->GetVertices();
	shoot::u16* pIndices = m_pEnvironment->GetMesh()->GetIndexBuffer(0)->Indices;
	shoot::s32 numIndices = m_pEnvironment->GetMesh()->GetIndexBuffer(0)->NumIndices;
	bool bFound = false;

	for(shoot::s32 i=0; i<numIndices; i += 3)
	{
		shoot::s32 newTriangleIndex = i/3;
		if(newTriangleIndex != m_iCurrentCollidingTriangle) // don't re-process the current colliding triangle
		{
			shoot::Vertex3D v1 = pVertices[pIndices[i + 0]];
			shoot::Vertex3D v2 = pVertices[pIndices[i + 1]];
			shoot::Vertex3D v3 = pVertices[pIndices[i + 2]];

			shoot::Plane plane(v1.Pos, v2.Pos, v3.Pos);

			// only process front facing planes			
			shoot::Plane::E_Classification eObjectClass = plane.ClassifyPoint(vPosition);

			if(eObjectClass == shoot::Plane::C_Front)
			{
				bool bInTheAir = IsInTheAir();
				bool bWall = IsWall(plane);
				shoot::Vector3D vTestVelocity;
				shoot::Vector3D vPointToCheck;

				if(bInTheAir || bWall)
				{
					vTestVelocity = vVelocity;
					vPointToCheck = vPosition - (plane.Normal*m_fRadius);
				}
				else
				{					
					vTestVelocity = shoot::Vector3D(0.0f, -1.0f, 0.0f);
					vPointToCheck = vPosition + shoot::Vector3D(0.0f, -m_fRadius, 0.0f);					
				}

				shoot::Vector3D normalizedVelocity = vTestVelocity;
				normalizedVelocity.Normalize();
				shoot::f32 cosAngle = (normalizedVelocity).DotProduct(plane.Normal);
				if(cosAngle < 0.0f)
				{									
					shoot::Vector3D vDestPoint = vPointToCheck + vTestVelocity;
					shoot::Vector3D vIntersection;
					shoot::Plane::E_Classification eClass;

					bool bIntersection = plane.IntersectWithRay(vPointToCheck, vTestVelocity, &vIntersection, &eClass);

					shoot::Triangle triangle(v1.Pos, v2.Pos, v3.Pos);
					bool bPointInside = bIntersection ? triangle.IsPointInside(vIntersection) : false;

					if(bIntersection && !bPointInside)
					{
						// check if point is on the triangle edges
						//bPointInside =  shoot::Math::IsPointOnLineSegment(vIntersection, triangle.A, triangle.B)
						//			 || shoot::Math::IsPointOnLineSegment(vIntersection, triangle.B, triangle.C)
						//			 || shoot::Math::IsPointOnLineSegment(vIntersection, triangle.C, triangle.A);				
					}

					if(bIntersection 
					&& bPointInside)
					{
						// determine class of dest point
						shoot::Plane::E_Classification eDestClass = plane.ClassifyPoint(vDestPoint);

						// if dest point is not front-facing the plane, we have a collision
						if(eDestClass != shoot::Plane::C_Front)				
						{
							m_pIntersection1->SetPosition(vIntersection);
							m_pIntersection1->GetMesh()->GetMaterial(0).SetColor(shoot::Color::Green);

							shoot::Print("Colliding with triangle '%d' - Normal (%.2f, %.2f, %.2f)\n", i/3, plane.Normal.X, plane.Normal.Y, plane.Normal.Z);				

							if(bWall)
							{
								vNewPosition = vIntersection + plane.Normal*m_fRadius;
								vNewVelocity = shoot::Vector3D(0.0f, 0.0f, 0.0f);														
							}
							else
							{
								vNewPosition = GetNewPosition(vPosition, vIntersection, plane);

								if(bInTheAir)
								{
									vNewVelocity = shoot::Vector3D(0.0f, 0.0f, 0.0f);
								}	

								m_vSlidingDirection = GetSlidingDirection(plane);
								m_iCurrentCollidingTriangle = newTriangleIndex;
							}
							
							shoot::Print("bWall = '%d', vNewVelocity(%.2f, %.2f, %.2f)\n", bWall, vNewVelocity.X, vNewVelocity.Y, vNewVelocity.Z);
							bFound = true;
							break;
						}				
					}			
				}		
			}
		}
	}

	if(!bFound)
	{
		// quickly check if still in contact with current triangle, if not then we are in the air!
		if(m_iCurrentCollidingTriangle >= 0)
		{
			
		}
	}
}
예제 #19
0
void tst_QPainterPath::closing()
{
    // lineto's
    {
        QPainterPath triangle(QPoint(100, 100));

        triangle.lineTo(200, 100);
        triangle.lineTo(200, 200);
        QCOMPARE(triangle.elementCount(), 3);

        triangle.closeSubpath();
        QCOMPARE(triangle.elementCount(), 4);
        QCOMPARE(triangle.elementAt(3).type, QPainterPath::LineToElement);

        triangle.moveTo(300, 300);
        QCOMPARE(triangle.elementCount(), 5);
        QCOMPARE(triangle.elementAt(4).type, QPainterPath::MoveToElement);

        triangle.lineTo(400, 300);
        triangle.lineTo(400, 400);
        QCOMPARE(triangle.elementCount(), 7);

        triangle.closeSubpath();
        QCOMPARE(triangle.elementCount(), 8);

        // this will should trigger implicit moveto...
        triangle.lineTo(600, 300);
        QCOMPARE(triangle.elementCount(), 10);
        QCOMPARE(triangle.elementAt(8).type, QPainterPath::MoveToElement);
        QCOMPARE(triangle.elementAt(9).type, QPainterPath::LineToElement);

        triangle.lineTo(600, 700);
        QCOMPARE(triangle.elementCount(), 11);
    }

    // curveto's
    {
        QPainterPath curves(QPoint(100, 100));

        curves.cubicTo(200, 100, 100, 200, 200, 200);
        QCOMPARE(curves.elementCount(), 4);

        curves.closeSubpath();
        QCOMPARE(curves.elementCount(), 5);
        QCOMPARE(curves.elementAt(4).type, QPainterPath::LineToElement);

        curves.moveTo(300, 300);
        QCOMPARE(curves.elementCount(), 6);
        QCOMPARE(curves.elementAt(5).type, QPainterPath::MoveToElement);

        curves.cubicTo(400, 300, 300, 400, 400, 400);
        QCOMPARE(curves.elementCount(), 9);

        curves.closeSubpath();
        QCOMPARE(curves.elementCount(), 10);

        // should trigger implicit moveto..
        curves.cubicTo(100, 800, 800, 100, 800, 800);
        QCOMPARE(curves.elementCount(), 14);
        QCOMPARE(curves.elementAt(10).type, QPainterPath::MoveToElement);
        QCOMPARE(curves.elementAt(11).type, QPainterPath::CurveToElement);
    }

    {
        QPainterPath rects;
        rects.addRect(100, 100, 100, 100);

        QCOMPARE(rects.elementCount(), 5);
        QCOMPARE(rects.elementAt(0).type, QPainterPath::MoveToElement);
        QCOMPARE(rects.elementAt(4).type, QPainterPath::LineToElement);

        rects.addRect(300, 100, 100,100);
        QCOMPARE(rects.elementCount(), 10);
        QCOMPARE(rects.elementAt(5).type, QPainterPath::MoveToElement);
        QCOMPARE(rects.elementAt(9).type, QPainterPath::LineToElement);

        rects.lineTo(0, 0);
        QCOMPARE(rects.elementCount(), 12);
        QCOMPARE(rects.elementAt(10).type, QPainterPath::MoveToElement);
        QCOMPARE(rects.elementAt(11).type, QPainterPath::LineToElement);
    }

    {
        QPainterPath ellipses;
        ellipses.addEllipse(100, 100, 100, 100);

        QCOMPARE(ellipses.elementCount(), 13);
        QCOMPARE(ellipses.elementAt(0).type, QPainterPath::MoveToElement);
        QCOMPARE(ellipses.elementAt(10).type, QPainterPath::CurveToElement);

        ellipses.addEllipse(300, 100, 100,100);
        QCOMPARE(ellipses.elementCount(), 26);
        QCOMPARE(ellipses.elementAt(13).type, QPainterPath::MoveToElement);
        QCOMPARE(ellipses.elementAt(23).type, QPainterPath::CurveToElement);

        ellipses.lineTo(0, 0);
        QCOMPARE(ellipses.elementCount(), 28);
        QCOMPARE(ellipses.elementAt(26).type, QPainterPath::MoveToElement);
        QCOMPARE(ellipses.elementAt(27).type, QPainterPath::LineToElement);
    }

    {
        QPainterPath path;
        path.moveTo(10, 10);
        path.lineTo(40, 10);
        path.lineTo(25, 20);
        path.lineTo(10 + 1e-13, 10 + 1e-13);
        QCOMPARE(path.elementCount(), 4);
        path.closeSubpath();
        QCOMPARE(path.elementCount(), 4);
    }
}
예제 #20
0
bool cycfig(int stage, int minbound)
{
    int testnum,testnum1;
    int testcase;
    switch(stage){
        case 1:
            for(testnum=10;testnum<100;testnum++){
                for(testnum1=testnum;testnum1<100;testnum1++){
                    if(triangle(testnum*100+testnum1)){
                        anscase[0]=3;
                        casefound[3]=true;
                        ans[0]=testnum;
                        ans[1]=testnum1;
                        if(cycfig(2,testnum))
                            return true;
                        casefound[3]=false;
                    }
                    if(square(testnum*100+testnum1)){
                        anscase[0]=4;
                        casefound[4]=true;
                        ans[0]=testnum;
                        ans[1]=testnum1;
                        if(cycfig(2,testnum))
                            return true;
                        casefound[4]=false;
                    }
                    if(pentagonal(testnum*100+testnum1)){
                        anscase[0]=5;
                        casefound[5]=true;
                        ans[0]=testnum;
                        ans[1]=testnum1;
                        if(cycfig(2,testnum))
                            return true;
                        casefound[5]=false;
                    }
                    if(hexagonal(testnum*100+testnum1)){
                        anscase[0]=6;
                        casefound[6]=true;
                        ans[0]=testnum;
                        ans[1]=testnum1;
                        if(cycfig(2,testnum))
                            return true;
                        casefound[6]=false;
                    }
                    if(heptagonal(testnum*100+testnum1)){
                        anscase[0]=7;
                        casefound[7]=true;
                        ans[0]=testnum;
                        ans[1]=testnum1;
                        if(cycfig(2,testnum))
                            return true;
                        casefound[7]=false;
                    }
                    if(octagonal(testnum*100+testnum1)){
                        anscase[0]=8;
                        casefound[8]=true;
                        ans[0]=testnum;
                        ans[1]=testnum1;
                        if(cycfig(2,testnum))
                            return true;
                        casefound[8]=false;
                    }
                }
            }
            break;
        case 2:
        case 3:
        case 4:
        case 5:
            for(testnum=minbound;testnum<100;testnum++){
                ans[stage]=testnum;
                for(testcase=3;testcase<9;testcase++){
                    if(casefound[testcase]==false){
                        switch(testcase){
                            case 3:
                                if(triangle(ans[stage-1]*100+ans[stage])){
                                    anscase[stage-1]=3;
                                    casefound[3]=true;
                                    if(cycfig(stage+1,minbound))
                                        return true;
                                    casefound[3]=false;
                                }
                                break;
                            case 4:
                                if(square(ans[stage-1]*100+ans[stage])){
                                    anscase[stage-1]=4;
                                    casefound[4]=true;
                                    if(cycfig(stage+1,minbound))
                                        return true;
                                    casefound[4]=false;
                                }
                                break;
                            case 5:
                                if(pentagonal(ans[stage-1]*100+ans[stage])){
                                    anscase[stage-1]=5;
                                    casefound[5]=true;
                                    if(cycfig(stage+1,minbound))
                                        return true;
                                    casefound[5]=false;
                                }
                                break;
                            case 6:
                                if(hexagonal(ans[stage-1]*100+ans[stage])){
                                    anscase[stage-1]=6;
                                    casefound[6]=true;
                                    if(cycfig(stage+1,minbound))
                                        return true;
                                    casefound[6]=false;
                                }
                                break;
                            case 7:
                                if(heptagonal(ans[stage-1]*100+ans[stage])){
                                    anscase[stage-1]=7;
                                    casefound[7]=true;
                                    if(cycfig(stage+1,minbound))
                                        return true;
                                    casefound[7]=false;
                                }
                                break;
                            case 8:
                                if(octagonal(ans[stage-1]*100+ans[stage])){
                                    anscase[stage-1]=8;
                                    casefound[8]=true;
                                    if(cycfig(stage+1,minbound))
                                        return true;
                                    casefound[8]=false;
                                }
                                break;
                            default: break;
                        }
                    }
                }
            }
            break;
        case 6:
            for(testcase=3;testcase<9;testcase++){
                if(!casefound[testcase]){
                    anscase[5]=testcase;
                    break;
                }
            }
            switch(testcase){
                case 3:
                    if(triangle(ans[5]*100+ans[0]))
                        return true;
                    break;
                case 4:
                    if(square(ans[5]*100+ans[0]))
                        return true;
                    break;
                case 5:
                    if(pentagonal(ans[5]*100+ans[0]))
                        return true;
                    break;
                case 6:
                    if(hexagonal(ans[5]*100+ans[0]))
                        return true;
                    break;
                case 7:
                    if(heptagonal(ans[5]*100+ans[0]))
                        return true;
                    break;
                case 8:
                    if(octagonal(ans[5]*100+ans[0]))
                        return true;
                    break;
                default: break;
            }
            break;
        default: return false;
    }
    return false;
}
예제 #21
0
파일: bitmap.cpp 프로젝트: prylee/Bitmap
void Bitmap::triangle(P2T pt) {
    triangle(pt.p1, pt.p2, pt.p3);
}
예제 #22
0
파일: ofApp.cpp 프로젝트: AditiSurana/oFGit
//--------------------------------------------------------------
void ofApp::draw(){
    square();
    triangle();
    circle();
}
예제 #23
0
TArray<FVector> equilateral_triangle(int32 upside_down, float length, FVector corner) {
	float base_to_height = sqrtf((float)3) / 2.0;
	return triangle(corner, far_corner(upside_down, length, corner), high_corner(upside_down, length, corner));
}
예제 #24
0
void ConvexDecompositionDemo::initPhysics(const char* filename)
{

	gContactAddedCallback = &MyContactCallback;

	setupEmptyDynamicsWorld();

	getDynamicsWorld()->setDebugDrawer(&gDebugDrawer);

	setTexturing(true);
	setShadows(true);

	setCameraDistance(26.f);


#ifndef NO_OBJ_TO_BULLET

	ConvexDecomposition::WavefrontObj wo;

	tcount = 0;
    const char* prefix[]={"./","../","../../","../../../","../../../../", "ConvexDecompositionDemo/", "Demos/ConvexDecompositionDemo/",
    "../Demos/ConvexDecompositionDemo/","../../Demos/ConvexDecompositionDemo/"};
    int numPrefixes = sizeof(prefix)/sizeof(const char*);
    char relativeFileName[1024];

    for (int i=0;i<numPrefixes;i++)
    {
        sprintf(relativeFileName,"%s%s",prefix[i],filename);
        tcount = wo.loadObj(relativeFileName);
        if (tcount)
            break;
    }



	btTransform startTransform;
	startTransform.setIdentity();
	startTransform.setOrigin(btVector3(0,-4.5,0));

	btCollisionShape* boxShape = new btBoxShape(btVector3(30,2,30));
	m_collisionShapes.push_back(boxShape);
	localCreateRigidBody(0.f,startTransform,boxShape);

	class MyConvexDecomposition : public ConvexDecomposition::ConvexDecompInterface
	{
		ConvexDecompositionDemo*	m_convexDemo;

		public:

		btAlignedObjectArray<btConvexHullShape*> m_convexShapes;
		btAlignedObjectArray<btVector3> m_convexCentroids;

		MyConvexDecomposition (FILE* outputFile,ConvexDecompositionDemo* demo)
			:m_convexDemo(demo),
				mBaseCount(0),
			mHullCount(0),
			mOutputFile(outputFile)

		{
		}

			virtual void ConvexDecompResult(ConvexDecomposition::ConvexResult &result)
			{

				btTriangleMesh* trimesh = new btTriangleMesh();
				m_convexDemo->m_trimeshes.push_back(trimesh);

				btVector3 localScaling(6.f,6.f,6.f);

				//export data to .obj
				printf("ConvexResult. ");
				if (mOutputFile)
				{
					fprintf(mOutputFile,"## Hull Piece %d with %d vertices and %d triangles.\r\n", mHullCount, result.mHullVcount, result.mHullTcount );

					fprintf(mOutputFile,"usemtl Material%i\r\n",mBaseCount);
					fprintf(mOutputFile,"o Object%i\r\n",mBaseCount);

					for (unsigned int i=0; i<result.mHullVcount; i++)
					{
						const float *p = &result.mHullVertices[i*3];
						fprintf(mOutputFile,"v %0.9f %0.9f %0.9f\r\n", p[0], p[1], p[2] );
					}

					//calc centroid, to shift vertices around center of mass
					centroid.setValue(0,0,0);

					btAlignedObjectArray<btVector3> vertices;
					if ( 1 )
					{
						//const unsigned int *src = result.mHullIndices;
						for (unsigned int i=0; i<result.mHullVcount; i++)
						{
							btVector3 vertex(result.mHullVertices[i*3],result.mHullVertices[i*3+1],result.mHullVertices[i*3+2]);
							vertex *= localScaling;
							centroid += vertex;

						}
					}

					centroid *= 1.f/(float(result.mHullVcount) );

					if ( 1 )
					{
						//const unsigned int *src = result.mHullIndices;
						for (unsigned int i=0; i<result.mHullVcount; i++)
						{
							btVector3 vertex(result.mHullVertices[i*3],result.mHullVertices[i*3+1],result.mHullVertices[i*3+2]);
							vertex *= localScaling;
							vertex -= centroid ;
							vertices.push_back(vertex);
						}
					}



					if ( 1 )
					{
						const unsigned int *src = result.mHullIndices;
						for (unsigned int i=0; i<result.mHullTcount; i++)
						{
							unsigned int index0 = *src++;
							unsigned int index1 = *src++;
							unsigned int index2 = *src++;


							btVector3 vertex0(result.mHullVertices[index0*3], result.mHullVertices[index0*3+1],result.mHullVertices[index0*3+2]);
							btVector3 vertex1(result.mHullVertices[index1*3], result.mHullVertices[index1*3+1],result.mHullVertices[index1*3+2]);
							btVector3 vertex2(result.mHullVertices[index2*3], result.mHullVertices[index2*3+1],result.mHullVertices[index2*3+2]);
							vertex0 *= localScaling;
							vertex1 *= localScaling;
							vertex2 *= localScaling;

							vertex0 -= centroid;
							vertex1 -= centroid;
							vertex2 -= centroid;


							trimesh->addTriangle(vertex0,vertex1,vertex2);

							index0+=mBaseCount;
							index1+=mBaseCount;
							index2+=mBaseCount;

							fprintf(mOutputFile,"f %d %d %d\r\n", index0+1, index1+1, index2+1 );
						}
					}

				//	float mass = 1.f;


//this is a tools issue: due to collision margin, convex objects overlap, compensate for it here:
//#define SHRINK_OBJECT_INWARDS 1
#ifdef SHRINK_OBJECT_INWARDS

					float collisionMargin = 0.01f;

					btAlignedObjectArray<btVector3> planeEquations;
					btGeometryUtil::getPlaneEquationsFromVertices(vertices,planeEquations);

					btAlignedObjectArray<btVector3> shiftedPlaneEquations;
					for (int p=0;p<planeEquations.size();p++)
					{
						btVector3 plane = planeEquations[p];
						plane[3] += collisionMargin;
						shiftedPlaneEquations.push_back(plane);
					}
					btAlignedObjectArray<btVector3> shiftedVertices;
					btGeometryUtil::getVerticesFromPlaneEquations(shiftedPlaneEquations,shiftedVertices);


					btConvexHullShape* convexShape = new btConvexHullShape(&(shiftedVertices[0].getX()),shiftedVertices.size());

#else //SHRINK_OBJECT_INWARDS

					btConvexHullShape* convexShape = new btConvexHullShape(&(vertices[0].getX()),vertices.size());
#endif
					if (sEnableSAT)
						convexShape->initializePolyhedralFeatures();
					convexShape->setMargin(0.01f);
					m_convexShapes.push_back(convexShape);
					m_convexCentroids.push_back(centroid);
					m_convexDemo->m_collisionShapes.push_back(convexShape);
					mBaseCount+=result.mHullVcount; // advance the 'base index' counter.


				}
			}

			int   	mBaseCount;
  			int		mHullCount;
			FILE*	mOutputFile;

	};

	if (tcount)
	{
		btTriangleMesh* trimesh = new btTriangleMesh();
		m_trimeshes.push_back(trimesh);

		btVector3 localScaling(6.f,6.f,6.f);

		int i;
		for ( i=0;i<wo.mTriCount;i++)
		{
			int index0 = wo.mIndices[i*3];
			int index1 = wo.mIndices[i*3+1];
			int index2 = wo.mIndices[i*3+2];

			btVector3 vertex0(wo.mVertices[index0*3], wo.mVertices[index0*3+1],wo.mVertices[index0*3+2]);
			btVector3 vertex1(wo.mVertices[index1*3], wo.mVertices[index1*3+1],wo.mVertices[index1*3+2]);
			btVector3 vertex2(wo.mVertices[index2*3], wo.mVertices[index2*3+1],wo.mVertices[index2*3+2]);

			vertex0 *= localScaling;
			vertex1 *= localScaling;
			vertex2 *= localScaling;

			trimesh->addTriangle(vertex0,vertex1,vertex2);
		}


		btConvexShape* tmpConvexShape = new btConvexTriangleMeshShape(trimesh);

		printf("old numTriangles= %d\n",wo.mTriCount);
		printf("old numIndices = %d\n",wo.mTriCount*3);
		printf("old numVertices = %d\n",wo.mVertexCount);

		printf("reducing vertices by creating a convex hull\n");

		//create a hull approximation
		btShapeHull* hull = new btShapeHull(tmpConvexShape);
		btScalar margin = tmpConvexShape->getMargin();
		hull->buildHull(margin);
		tmpConvexShape->setUserPointer(hull);


		printf("new numTriangles = %d\n", hull->numTriangles ());
		printf("new numIndices = %d\n", hull->numIndices ());
		printf("new numVertices = %d\n", hull->numVertices ());

		btConvexHullShape* convexShape = new btConvexHullShape();
		bool updateLocalAabb = false;

		for (i=0;i<hull->numVertices();i++)
		{
			convexShape->addPoint(hull->getVertexPointer()[i],updateLocalAabb);
		}
		convexShape->recalcLocalAabb();

		if (sEnableSAT)
			convexShape->initializePolyhedralFeatures();
		delete tmpConvexShape;
		delete hull;



		m_collisionShapes.push_back(convexShape);

		float mass = 1.f;

		btTransform startTransform;
		startTransform.setIdentity();
		startTransform.setOrigin(btVector3(0,2,14));

		localCreateRigidBody(mass, startTransform,convexShape);

		bool useQuantization = true;
		btCollisionShape* concaveShape = new btBvhTriangleMeshShape(trimesh,useQuantization);
		startTransform.setOrigin(convexDecompositionObjectOffset);
		localCreateRigidBody(0.f,startTransform,concaveShape);

		m_collisionShapes.push_back (concaveShape);

	}


	if (tcount)
	{
		//-----------------------------------
		// Bullet Convex Decomposition
		//-----------------------------------

		char outputFileName[512];
  		strcpy(outputFileName,filename);
  		char *dot = strstr(outputFileName,".");
  		if ( dot )
			*dot = 0;
		strcat(outputFileName,"_convex.obj");
  		FILE* outputFile = fopen(outputFileName,"wb");

		unsigned int depth = 5;
		float cpercent     = 5;
		float ppercent     = 15;
		unsigned int maxv  = 16;
		float skinWidth    = 0.0;

		printf("WavefrontObj num triangles read %i\n",tcount);
		ConvexDecomposition::DecompDesc desc;
		desc.mVcount       = wo.mVertexCount;
		desc.mVertices     = wo.mVertices;
		desc.mTcount       = wo.mTriCount;
		desc.mIndices      = (unsigned int *)wo.mIndices;
		desc.mDepth        = depth;
		desc.mCpercent     = cpercent;
		desc.mPpercent     = ppercent;
		desc.mMaxVertices  = maxv;
		desc.mSkinWidth    = skinWidth;

		MyConvexDecomposition	convexDecomposition(outputFile,this);
		desc.mCallback = &convexDecomposition;


		//-----------------------------------------------
		// HACD
		//-----------------------------------------------

		std::vector< HACD::Vec3<HACD::Real> > points;
		std::vector< HACD::Vec3<long> > triangles;

		for(int i=0; i<wo.mVertexCount; i++ )
		{
			int index = i*3;
			HACD::Vec3<HACD::Real> vertex(wo.mVertices[index], wo.mVertices[index+1],wo.mVertices[index+2]);
			points.push_back(vertex);
		}

		for(int i=0;i<wo.mTriCount;i++)
		{
			int index = i*3;
			HACD::Vec3<long> triangle(wo.mIndices[index], wo.mIndices[index+1], wo.mIndices[index+2]);
			triangles.push_back(triangle);
		}


		HACD::HACD myHACD;
		myHACD.SetPoints(&points[0]);
		myHACD.SetNPoints(points.size());
		myHACD.SetTriangles(&triangles[0]);
		myHACD.SetNTriangles(triangles.size());
		myHACD.SetCompacityWeight(0.1);
		myHACD.SetVolumeWeight(0.0);

		// HACD parameters
		// Recommended parameters: 2 100 0 0 0 0
		size_t nClusters = 2;
		double concavity = 100;
		bool invert = false;
		bool addExtraDistPoints = false;
		bool addNeighboursDistPoints = false;
		bool addFacesPoints = false;

		myHACD.SetNClusters(nClusters);                     // minimum number of clusters
		myHACD.SetNVerticesPerCH(100);                      // max of 100 vertices per convex-hull
		myHACD.SetConcavity(concavity);                     // maximum concavity
		myHACD.SetAddExtraDistPoints(addExtraDistPoints);
		myHACD.SetAddNeighboursDistPoints(addNeighboursDistPoints);
		myHACD.SetAddFacesPoints(addFacesPoints);

		myHACD.Compute();
		nClusters = myHACD.GetNClusters();

		myHACD.Save("output.wrl", false);


		//convexDecomposition.performConvexDecomposition(desc);

//		ConvexBuilder cb(desc.mCallback);
//		cb.process(desc);
		//now create some bodies

		if (1)
		{
			btCompoundShape* compound = new btCompoundShape();
			m_collisionShapes.push_back (compound);

			btTransform trans;
			trans.setIdentity();

			for (int c=0;c<nClusters;c++)
			{
				//generate convex result
				size_t nPoints = myHACD.GetNPointsCH(c);
				size_t nTriangles = myHACD.GetNTrianglesCH(c);

				float* vertices = new float[nPoints*3];
				unsigned int* triangles = new unsigned int[nTriangles*3];

				HACD::Vec3<HACD::Real> * pointsCH = new HACD::Vec3<HACD::Real>[nPoints];
				HACD::Vec3<long> * trianglesCH = new HACD::Vec3<long>[nTriangles];
				myHACD.GetCH(c, pointsCH, trianglesCH);

				// points
				for(size_t v = 0; v < nPoints; v++)
				{
					vertices[3*v] = pointsCH[v].X();
					vertices[3*v+1] = pointsCH[v].Y();
					vertices[3*v+2] = pointsCH[v].Z();
				}
				// triangles
				for(size_t f = 0; f < nTriangles; f++)
				{
					triangles[3*f] = trianglesCH[f].X();
					triangles[3*f+1] = trianglesCH[f].Y();
					triangles[3*f+2] = trianglesCH[f].Z();
				}

				delete [] pointsCH;
				delete [] trianglesCH;

				ConvexResult r(nPoints, vertices, nTriangles, triangles);
				convexDecomposition.ConvexDecompResult(r);
			}

			for (int i=0;i<convexDecomposition.m_convexShapes.size();i++)
			{
				btVector3 centroid = convexDecomposition.m_convexCentroids[i];
				trans.setOrigin(centroid);
				btConvexHullShape* convexShape = convexDecomposition.m_convexShapes[i];
				compound->addChildShape(trans,convexShape);

				btRigidBody* body;
				body = localCreateRigidBody( 1.0, trans,convexShape);
			}
/*			for (int i=0;i<convexDecomposition.m_convexShapes.size();i++)
			{

				btVector3 centroid = convexDecomposition.m_convexCentroids[i];
				trans.setOrigin(centroid);
				btConvexHullShape* convexShape = convexDecomposition.m_convexShapes[i];
				compound->addChildShape(trans,convexShape);

				btRigidBody* body;
				body = localCreateRigidBody( 1.0, trans,convexShape);
			}*/

#if 1
			btScalar mass=10.f;
			trans.setOrigin(-convexDecompositionObjectOffset);
			btRigidBody* body = localCreateRigidBody( mass, trans,compound);
			body->setCollisionFlags(body->getCollisionFlags() |   btCollisionObject::CF_CUSTOM_MATERIAL_CALLBACK);

			convexDecompositionObjectOffset.setZ(6);
			trans.setOrigin(-convexDecompositionObjectOffset);
			body = localCreateRigidBody( mass, trans,compound);
			body->setCollisionFlags(body->getCollisionFlags() |   btCollisionObject::CF_CUSTOM_MATERIAL_CALLBACK);

			convexDecompositionObjectOffset.setZ(-6);
			trans.setOrigin(-convexDecompositionObjectOffset);
			body = localCreateRigidBody( mass, trans,compound);
			body->setCollisionFlags(body->getCollisionFlags() |   btCollisionObject::CF_CUSTOM_MATERIAL_CALLBACK);
#endif
		}


		if (outputFile)
			fclose(outputFile);


	}



#ifdef TEST_SERIALIZATION
	//test serializing this

	int maxSerializeBufferSize = 1024*1024*5;

	btDefaultSerializer*	serializer = new btDefaultSerializer(maxSerializeBufferSize);
	m_dynamicsWorld->serialize(serializer);

	FILE* f2 = fopen("testFile.bullet","wb");
	fwrite(serializer->getBufferPointer(),serializer->getCurrentBufferSize(),1,f2);
	fclose(f2);

	exitPhysics();

	//now try again from the loaded file
	setupEmptyDynamicsWorld();
#endif //TEST_SERIALIZATION

#endif //NO_OBJ_TO_BULLET

#ifdef TEST_SERIALIZATION

	btBulletWorldImporter* fileLoader = new btBulletWorldImporter(m_dynamicsWorld);
	//fileLoader->setVerboseMode(true);

	fileLoader->loadFile("testFile.bullet");
	//fileLoader->loadFile("testFile64Double.bullet");
	//fileLoader->loadFile("testFile64Single.bullet");
	//fileLoader->loadFile("testFile32Single.bullet");




#endif //TEST_SERIALIZATION

}
예제 #25
0
파일: smooth.c 프로젝트: andreaswatch/dizuo
void display(void)
{
   glClear (GL_COLOR_BUFFER_BIT);
   triangle ();
   glFlush ();
}
예제 #26
0
void WebTestThemeEngineMock::paint(
    blink::WebCanvas* canvas,
    WebThemeEngine::Part part,
    WebThemeEngine::State state,
    const blink::WebRect& rect,
    const WebThemeEngine::ExtraParams* extraParams)
{
    SkIRect irect = webRectToSkIRect(rect);
    SkPaint paint;

    // Indent amounts for the check in a checkbox or radio button.
    const int checkIndent = 3;

    // Indent amounts for short and long sides of the scrollbar notches.
    const int notchLongOffset = 1;
    const int notchShortOffset = 4;
    const int noOffset = 0;

    // Indent amounts for the short and long sides of a scroll thumb box.
    const int thumbLongIndent = 0;
    const int thumbShortIndent = 2;

    // Indents for the crosshatch on a scroll grip.
    const int gripLongIndent = 3;
    const int gripShortIndent = 5;

    // Indents for the the slider track.
    const int sliderIndent = 2;

    int halfHeight = irect.height() / 2;
    int halfWidth = irect.width() / 2;
    int quarterHeight = irect.height() / 4;
    int quarterWidth = irect.width() / 4;
    int left = irect.fLeft;
    int right = irect.fRight;
    int top = irect.fTop;
    int bottom = irect.fBottom;

    switch (part) {
    case WebThemeEngine::PartScrollbarDownArrow:
        box(canvas, irect, bgColors[state]);
        triangle(canvas,
            left  + quarterWidth, top    + quarterHeight,
            right - quarterWidth, top    + quarterHeight,
            left  + halfWidth,    bottom - quarterHeight,
            edgeColor);
        markState(canvas, irect, state);
        break;

    case WebThemeEngine::PartScrollbarLeftArrow:
        box(canvas, irect, bgColors[state]);
        triangle(canvas,
            right - quarterWidth, top    + quarterHeight,
            right - quarterWidth, bottom - quarterHeight,
            left  + quarterWidth, top    + halfHeight,
            edgeColor);
        break;

    case WebThemeEngine::PartScrollbarRightArrow:
        box(canvas, irect, bgColors[state]);
        triangle(canvas,
            left  + quarterWidth, top    + quarterHeight,
            right - quarterWidth, top    + halfHeight,
            left  + quarterWidth, bottom - quarterHeight,
            edgeColor);
        break;

    case WebThemeEngine::PartScrollbarUpArrow:
        box(canvas, irect, bgColors[state]);
        triangle(canvas,
            left  + quarterWidth, bottom - quarterHeight,
            left  + halfWidth,    top    + quarterHeight,
            right - quarterWidth, bottom - quarterHeight,
            edgeColor);
        markState(canvas, irect, state);
        break;

    case WebThemeEngine::PartScrollbarHorizontalThumb: {
        // Draw a narrower box on top of the outside box.
        nestedBoxes(canvas, irect, thumbLongIndent, thumbShortIndent,
            thumbLongIndent, thumbShortIndent,
            bgColors[state], bgColors[state]);
        // Draw a horizontal crosshatch for the grip.
        int longOffset = halfWidth - gripLongIndent;
        line(canvas,
            left  + gripLongIndent, top    + halfHeight,
            right - gripLongIndent, top    + halfHeight,
            edgeColor);
        line(canvas,
            left  + longOffset,     top    + gripShortIndent,
            left  + longOffset,     bottom - gripShortIndent,
            edgeColor);
        line(canvas,
            right - longOffset,     top    + gripShortIndent,
            right - longOffset,     bottom - gripShortIndent,
            edgeColor);
        markState(canvas, irect, state);
        break;
    }

    case WebThemeEngine::PartScrollbarVerticalThumb: {
        // Draw a shorter box on top of the outside box.
        nestedBoxes(canvas, irect, thumbShortIndent, thumbLongIndent,
            thumbShortIndent, thumbLongIndent,
            bgColors[state], bgColors[state]);
        // Draw a vertical crosshatch for the grip.
        int longOffset = halfHeight - gripLongIndent;
        line(canvas,
            left  + halfWidth,       top    + gripLongIndent,
            left  + halfWidth,       bottom - gripLongIndent,
            edgeColor);
        line(canvas,
            left  + gripShortIndent, top    + longOffset,
            right - gripShortIndent, top    + longOffset,
            edgeColor);
        line(canvas,
            left  + gripShortIndent, bottom - longOffset,
            right - gripShortIndent, bottom - longOffset,
            edgeColor);
        markState(canvas, irect, state);
        break;
    }

    case WebThemeEngine::PartScrollbarHorizontalTrack: {
        int longOffset = halfHeight - notchLongOffset;
        int shortOffset = irect.width() - notchShortOffset;
        if (extraParams->scrollbarTrack.isBack) {
            // back, notch on left
            nestedBoxes(canvas, irect, noOffset, longOffset, shortOffset,
                longOffset, bgColors[state], edgeColor);
        } else {
            // forward, notch on right
            nestedBoxes(canvas, irect, shortOffset, longOffset, noOffset,
                longOffset, bgColors[state], edgeColor);
        }

        markState(canvas, irect, state);
        break;
    }

    case WebThemeEngine::PartScrollbarVerticalTrack: {
        int longOffset = halfWidth - notchLongOffset;
        int shortOffset = irect.height() - notchShortOffset;
        if (extraParams->scrollbarTrack.isBack) {
            // back, notch at top
            nestedBoxes(canvas, irect, longOffset, noOffset, longOffset,
                shortOffset, bgColors[state], edgeColor);
        } else {
            // forward, notch at bottom
            nestedBoxes(canvas, irect, longOffset, shortOffset, longOffset,
                noOffset, bgColors[state], edgeColor);
        }

        markState(canvas, irect, state);
        break;
    }

    case WebThemeEngine::PartCheckbox:
        if (extraParams->button.indeterminate) {
            nestedBoxes(canvas, irect,
                checkIndent, halfHeight,
                checkIndent, halfHeight,
                bgColors[state], edgeColor);
        } else if (extraParams->button.checked) {
            irect = validate(irect, part);
            nestedBoxes(canvas, irect,
                checkIndent, checkIndent,
                checkIndent, checkIndent,
                bgColors[state], edgeColor);
        } else {
            irect = validate(irect, part);
            box(canvas, irect, bgColors[state]);
        }
        break;

    case WebThemeEngine::PartRadio:
        irect = validate(irect, part);
        halfHeight = irect.height() / 2;
        if (extraParams->button.checked) {
            circle(canvas, irect, SkIntToScalar(halfHeight), bgColors[state]);
            circle(canvas, irect, SkIntToScalar(halfHeight - checkIndent), edgeColor);
        } else {
            circle(canvas, irect, SkIntToScalar(halfHeight), bgColors[state]);
        }
        break;

    case WebThemeEngine::PartButton:
        roundRect(canvas, irect, bgColors[state]);
        markState(canvas, irect, state);
        break;

    case WebThemeEngine::PartTextField:
        paint.setColor(extraParams->textField.backgroundColor);
        paint.setStyle(SkPaint::kFill_Style);
        canvas->drawIRect(irect, paint);

        paint.setColor(edgeColor);
        paint.setStyle(SkPaint::kStroke_Style);
        canvas->drawIRect(irect, paint);

        markState(canvas, irect, state);
        break;

    case WebThemeEngine::PartMenuList:
        if (extraParams->menuList.fillContentArea) {
            box(canvas, irect, extraParams->menuList.backgroundColor);
        } else {
            SkPaint paint;
            paint.setColor(edgeColor);
            paint.setStyle(SkPaint::kStroke_Style);
            canvas->drawIRect(irect, paint);
        }

        // clip the drop-down arrow to be inside the select box
        if (extraParams->menuList.arrowX - 4 > irect.fLeft)
            irect.fLeft = extraParams->menuList.arrowX - 4;
        if (extraParams->menuList.arrowX + 12 < irect.fRight)
            irect.fRight = extraParams->menuList.arrowX + 12;

        irect.fTop = extraParams->menuList.arrowY - (extraParams->menuList.arrowHeight) / 2;
        irect.fBottom = extraParams->menuList.arrowY + (extraParams->menuList.arrowHeight - 1) / 2;
        halfWidth = irect.width() / 2;
        quarterWidth = irect.width() / 4;

        if (state == WebThemeEngine::StateFocused) // FIXME: draw differenty?
            state = WebThemeEngine::StateNormal;
        box(canvas, irect, bgColors[state]);
        triangle(canvas,
            irect.fLeft  + quarterWidth, irect.fTop,
            irect.fRight - quarterWidth, irect.fTop,
            irect.fLeft  + halfWidth,    irect.fBottom,
            edgeColor);

        break;

    case WebThemeEngine::PartSliderTrack: {
        SkIRect lirect =  irect;

        // Draw a narrow rect for the track plus box hatches on the ends.
        if (state == WebThemeEngine::StateFocused) // FIXME: draw differently?
            state = WebThemeEngine::StateNormal;
        if (extraParams->slider.vertical) {
            lirect.inset(halfWidth - sliderIndent, noOffset);
            box(canvas, lirect, bgColors[state]);
            line(canvas, left, top, right, top, edgeColor);
            line(canvas, left, bottom, right, bottom, edgeColor);
        } else {
            lirect.inset(noOffset, halfHeight - sliderIndent);
            box(canvas, lirect, bgColors[state]);
            line(canvas, left, top, left, bottom, edgeColor);
            line(canvas, right, top, right, bottom, edgeColor);
        }
        break;
    }

    case WebThemeEngine::PartSliderThumb:
        if (state == WebThemeEngine::StateFocused) // FIXME: draw differently?
            state = WebThemeEngine::StateNormal;
        oval(canvas, irect, bgColors[state]);
        break;

    case WebThemeEngine::PartInnerSpinButton: {
        // stack half-height up and down arrows on top of each other
        SkIRect lirect;
        int halfHeight = rect.height / 2;
        if (extraParams->innerSpin.readOnly)
            state = blink::WebThemeEngine::StateDisabled;

        lirect.set(rect.x, rect.y, rect.x + rect.width - 1, rect.y + halfHeight - 1);
        box(canvas, lirect, bgColors[state]);
        bottom = lirect.fBottom;
        quarterHeight = lirect.height() / 4;
        triangle(canvas,
            left  + quarterWidth, bottom - quarterHeight,
            right - quarterWidth, bottom - quarterHeight,
            left  + halfWidth,    top    + quarterHeight,
            edgeColor);

        lirect.set(rect.x, rect.y + halfHeight, rect.x + rect.width - 1,
            rect.y + 2 * halfHeight - 1);
        top = lirect.fTop;
        bottom = lirect.fBottom;
        quarterHeight = lirect.height() / 4;
        box(canvas, lirect, bgColors[state]);
        triangle(canvas,
            left  + quarterWidth, top    + quarterHeight,
            right - quarterWidth, top    + quarterHeight,
            left  + halfWidth,    bottom - quarterHeight,
            edgeColor);
        markState(canvas, irect, state);
        break;
    }
    case WebThemeEngine::PartProgressBar: {
        paint.setColor(bgColors[state]);
        paint.setStyle(SkPaint::kFill_Style);
        canvas->drawIRect(irect, paint);

        // Emulate clipping
        SkIRect tofill = irect;
        if (extraParams->progressBar.determinate) {
            tofill.set(extraParams->progressBar.valueRectX,
                extraParams->progressBar.valueRectY,
                extraParams->progressBar.valueRectX +
                extraParams->progressBar.valueRectWidth - 1,
                extraParams->progressBar.valueRectY +
                extraParams->progressBar.valueRectHeight);
        }

        tofill.intersect(irect, tofill);
        paint.setColor(edgeColor);
        paint.setStyle(SkPaint::kFill_Style);
        canvas->drawIRect(tofill, paint);

        markState(canvas, irect, state);
        break;
    }
    default:
        // FIXME: Should we do something here to indicate that we got an invalid part?
        // Unfortunately, we can't assert because we don't have access to WTF or base.
        break;
    }
}
예제 #27
0
//collision move sphere with triangle
bool kgmCollision::collision(vec3& start, vec3& end, float radius, vec3& tra, vec3& trb,
                             vec3& trc, vec3& pt_insect)
{
  triangle3 triangle(tra, trb, trc);
  plane3    plane(tra, trb, trc);
  line3     line(start, end);

  float s_dist = plane.distance(start),
        e_dist = plane.distance(end);

  bool b_plinsect = false;
  bool b_plnear = false;

  if(s_dist < 0.0) return false;

  if(plane.intersect(line, pt_insect))
  {
    b_plinsect = true;
  }

  if((e_dist >= 0.0f) && (e_dist < radius))
  {
    pt_insect = plane.projection(end);
    b_plnear = true;
  }

  if(!b_plinsect && !b_plnear)
  {
    return false;
  }

  if(b_plinsect || b_plnear)
  {
    //  return true;
  }

  if(triangle.isin(pt_insect))
  {
    m_point = pt_insect;
    m_normal = plane.normal();

    return true;
  }

  sphere3 sphere(pt_insect, radius);
  /* if(sphere.isin(tra) || sphere.isin(trb) || sphere.isin(trc)){
   m_point = pt_insect;
   m_normal = plane.normal();
   return true;
 }
//*/

  line3 lna(tra, trb), lnb(trb, trc), lnc(trc, tra);

  if(crossLineSphere(lna, sphere) ||
     crossLineSphere(lnb, sphere) ||
     crossLineSphere(lnc, sphere))
  {
    m_point = pt_insect;
    m_normal = plane.normal();

    return true;
  }

  return false;
}
예제 #28
0
파일: main.cpp 프로젝트: Proudmoor/OpenGL
void tetra(const point3& a, const point3& b, const point3& c, const point3& d){
    triangle(a, b, c, 0);
    triangle(a, c, d, 1);
    triangle(a, d, b, 2);
    triangle(b, d, c, 3);
}
예제 #29
0
void kgmMesh::rebuild()
{
  if (m_linked)
    return;

  if(!m_vertices)
    return;

  u8 *v = (u8*) m_vertices;
  vec3 max = ((Vertex*)v)->pos,
       min = ((Vertex*)v)->pos;

  u32 i    = 0;
  u32 size = vsize();

  for(i = 1; i < m_vcount; i++)
  {
    v += size;

    Vertex* vt = (Vertex*)v;

    min.x = MIN(min.x, ((Vertex*)v)->pos.x);
    min.y = MIN(min.y, ((Vertex*)v)->pos.y);
    min.z = MIN(min.z, ((Vertex*)v)->pos.z);
    max.x = MAX(max.x, ((Vertex*)v)->pos.x);
    max.y = MAX(max.y, ((Vertex*)v)->pos.y);
    max.z = MAX(max.z, ((Vertex*)v)->pos.z);
  }

  m_bound.min = min;
  m_bound.max = max;

  u8* f     = (u8*)m_faces;

  if (!f)
    return;

  v = (u8*) m_vertices;

  if (!v)
    return;

  m_normal = vec3(0, 0, 0);

  i = 0;

  for (i = 0; i < m_fcount; i++)
  {
    triangle tr;
    Face*    fc = (Face*)f;

    Vertex *v1, *v2, *v3;
    u32     f1,  f2,  f3;

    if (m_fff == FFF_16) {
      f1 = ((Face_16*)fc)->a;
      f2 = ((Face_16*)fc)->b;
      f3 = ((Face_16*)fc)->c;
    } else {
      f1 = ((Face_32*)fc)->a;
      f2 = ((Face_32*)fc)->b;
      f3 = ((Face_32*)fc)->c;
    }

    v1 = (Vertex*) ((u8*)m_vertices + vsize() * f1);
    v2 = (Vertex*) ((u8*)m_vertices + vsize() * f2);
    v3 = (Vertex*) ((u8*)m_vertices + vsize() * f3);

    tr = triangle(v1->pos, v2->pos, v3->pos);

    vec3 n = tr.normal();

    n.normalize();
    m_normal = m_normal + n;

    f += fsize();
  }

  m_normal.normalize();
}
예제 #30
0
void CALLBACK Paint(void)
{
	glClear(GL_COLOR_BUFFER_BIT);
	triangle();
	glFlush();
}