예제 #1
0
//----------------------------------------------------
void CRocketLauncher::UpdateTPLaser(float frameTime)
{
	m_lastUpdate -= frameTime;

	bool allowUpdate = true;
	if(m_lastUpdate<=0.0f)
		m_lastUpdate = m_Timeout;
	else
		allowUpdate = false;

	const CCamera& camera = gEnv->pRenderer->GetCamera();

	//If character not visible, laser is not correctly updated
	if(CActor* pOwner = GetOwnerActor())
	{
		ICharacterInstance* pCharacter = pOwner->GetEntity()->GetCharacter(0);
		if(pCharacter && !pCharacter->IsCharacterVisible())
			return;
	}

	Vec3   offset(-0.06f,0.28f,0.115f); //To match scope position in TP LAW model
	Vec3   pos = GetEntity()->GetWorldTM().TransformPoint(offset);
	Vec3   dir = GetEntity()->GetWorldRotation().GetColumn1();

	Vec3 hitPos(0,0,0);
	float laserLength = 0.0f;

	if(allowUpdate)
	{
		IPhysicalEntity* pSkipEntity = NULL;
		if(GetOwner())
			pSkipEntity = GetOwner()->GetPhysics();

		const float range = m_LaserRangeTP;

		// Use the same flags as the AI system uses for visibility.
		const int objects = ent_terrain|ent_static|ent_rigid|ent_sleeping_rigid|ent_independent; //ent_living;
		const int flags = (geom_colltype_ray << rwi_colltype_bit) | rwi_colltype_any | (10 & rwi_pierceability_mask) | (geom_colltype14 << rwi_colltype_bit);

		ray_hit hit;
		if (gEnv->pPhysicalWorld->RayWorldIntersection(pos, dir*range, objects, flags,
			&hit, 1, &pSkipEntity, pSkipEntity ? 1 : 0))
		{
			laserLength = hit.dist;
			m_lastLaserHitPt = hit.pt;
			m_lastLaserHitSolid = true;
		}
		else
		{
			m_lastLaserHitSolid = false;
			m_lastLaserHitPt = pos + dir * range;
			laserLength = range + 0.1f;
		}

		// Hit near plane
		if (dir.Dot(camera.GetViewdir()) < 0.0f)
		{
			Plane nearPlane;
			nearPlane.SetPlane(camera.GetViewdir(), camera.GetPosition());
			nearPlane.d -= camera.GetNearPlane()+0.15f;
			Ray ray(pos, dir);
			Vec3 out;
			m_lastLaserHitViewPlane = false;
			if (Intersect::Ray_Plane(ray, nearPlane, out))
			{
				float dist = Distance::Point_Point(pos, out);
				if (dist < laserLength)
				{
					laserLength = dist;
					m_lastLaserHitPt = out;
					m_lastLaserHitSolid = true;
					m_lastLaserHitViewPlane = true;
				}
			}
		}

		hitPos = m_lastLaserHitPt;
	}
	else
	{
		laserLength = Distance::Point_Point(m_lastLaserHitPt, pos);
		hitPos = pos + dir * laserLength;
	}

	if (m_smoothLaserLength < 0.0f)
		m_smoothLaserLength = laserLength;
	else
	{
		if (laserLength < m_smoothLaserLength)
			m_smoothLaserLength = laserLength;
		else
			m_smoothLaserLength += (laserLength - m_smoothLaserLength) * min(1.0f, 10.0f * frameTime);
	}

	const float assetLength = 2.0f;
	m_smoothLaserLength = CLAMP(m_smoothLaserLength,0.01f,m_LaserRangeTP);
	float scale = m_smoothLaserLength / assetLength; 

	// Scale the laser based on the distance.
	Matrix34 scl;
	scl.SetIdentity();
	scl.SetScale(Vec3(1,scale,1));
	scl.SetTranslation(offset);
	GetEntity()->SetSlotLocalTM( eIGS_Aux1, scl);

	if (m_dotEffectSlot >= 0)
	{
		if (m_lastLaserHitSolid)
		{
			Matrix34 dotMatrix = Matrix34::CreateTranslationMat(Vec3(0,m_smoothLaserLength,0));
			dotMatrix.AddTranslation(offset);
			if(m_lastLaserHitViewPlane)
				dotMatrix.Scale(Vec3(0.2f,0.2f,0.2f));
			GetEntity()->SetSlotLocalTM(m_dotEffectSlot,dotMatrix);
		}
		else
		{
			Matrix34 scaleMatrix;
			scaleMatrix.SetIdentity();
			scaleMatrix.SetScale(Vec3(0.001f,0.001f,0.001f));
			GetEntity()->SetSlotLocalTM(m_dotEffectSlot, scaleMatrix);
		}
	}
}
예제 #2
0
// line perpendicular to a plane at a specific point
Line::Line(const Plane& _plane, const Point& _point)
{
	Line(_plane.getNormalVector(), _point);
}
예제 #3
0
파일: main_pk.cpp 프로젝트: Goobae/Shapes
void DrawScene(Window * window)
{
	phong_shader.GLReturnedError("DrawScene() - entering");
#ifdef MOVE
	mat4 m = rotate(mat4() , radians(window->LocalTime() * 30.0f) , vec3(0.0f , 1.0f , 0.2f));
	m = translate(m, vec3(0.0f, 11.5f * cos(window->LocalTime() * 0.5f) + 2.0f, 11.5f * sin(window->LocalTime() * 0.5f) + 2.0f));
#else
	mat4 m;
#endif // MOVE

	mat4 view_matrix = lookAt(vec3(m * vec4(eye, 1.0f)), cop, up);
	mat4 model_matrix;
	mat4 projection_matrix = perspective(radians(window->fovy), window->aspect, window->near_distance, window->far_distance);

	vec3 z_axis = vec3(0.0f, 0.0f, 1.0f);
	vec3 y_axis = vec3(0.0f, 1.0f, 0.0f);
	vec3 ambient = vec3(0.1f, 0.1f, 0.1f);
	vec3 specular = vec3(1.0f, 1.0f, 1.0f);
	float c_offset = radians(45.0f);

	glViewport(0, 0, window->size.x, window->size.y);

	const int count_of_shapes = 4;

	for (unsigned int i = 0; i < instances.size(); i++)
	{
		model_matrix = translate(mat4(), instances[i].position);
		model_matrix = rotate(model_matrix, radians(window->LocalTime() * instances[i].rate) + instances[i].offset, y_axis);
		if (i % count_of_shapes == 3)
			model_matrix = scale(model_matrix, vec3(0.25f, 0.25f, 0.25f));

		phong_shader.Use(model_matrix, view_matrix, projection_matrix);
		phong_shader.SetMaterial(instances[i].diffuse, specular, 32.0f, ambient);
		phong_shader.SetLightPosition(vec3(0.0f, 0.0f, 1000.0f));

		switch (i % count_of_shapes)
		{
		case 0:
			disc1.Draw(false);
			break;
		case 1:
			disc3.Draw(false);
			break;
		case 2:
			plane2.Draw(false);
			break;
		case 3:
			cube.Draw(false);
			break;
		}
		phong_shader.UnUse();

		#ifdef SHOW_NORMALS
		if (i == 0)
		{
			constant_shader.Use(model_matrix, view_matrix, projection_matrix);
			constant_shader.SetMaterial(vec3(0.0f, 0.0f, 0.8f), specular, 128.0f, vec3(1.0f, 0.0f, 0.0f));
			disc1.Draw(true);
			constant_shader.UnUse();
		}
		#endif
	}

	model_matrix = mat4();
	mat4 mz = model_matrix;
	model_matrix = scale(model_matrix, vec3(0.5f, 0.5f, 16.0f));

	phong_shader.Use(model_matrix, view_matrix, projection_matrix);
	phong_shader.SetMaterial(vec3(0.0f, 0.0f, 0.8f), specular, 128.0f, ambient);
	phong_shader.SetLightPosition(vec3(0.0f, 1000.0f, 0.0f));
	cylinder1.Draw(false);
	phong_shader.UnUse();

#ifdef SHOW_NORMALS
	constant_shader.Use(model_matrix, view_matrix, projection_matrix);
	constant_shader.SetMaterial(vec3(0.0f, 0.0f, 0.8f), specular, 128.0f, vec3(1.0f, 1.0f, 1.0f));
	cylinder.Draw(true);
	constant_shader.UnUse();
#endif

	model_matrix = rotate(mz, radians(90.0f), y_axis);
	model_matrix = scale(model_matrix, vec3(0.5f, 0.5f, 16.0f));
	phong_shader.Use(model_matrix, view_matrix, projection_matrix);
	phong_shader.SetMaterial(vec3(1.0f, 0.0f, 0.0f), specular, 128.0f, ambient);
	phong_shader.SetLightPosition(vec3(0.0f, 1000.0f, 0.0f));
	cylinder1.Draw(false);
	phong_shader.UnUse();

	model_matrix = rotate(mz, radians(-90.0f), vec3(1.0f, 0.0f, 0.0f));
	model_matrix = scale(model_matrix, vec3(0.5f, 0.5f, 16.0f));
	phong_shader.Use(model_matrix, view_matrix, projection_matrix);
	phong_shader.SetMaterial(vec3(0.0f, 1.0f, 0.0f), specular, 128.0f, ambient);
	phong_shader.SetLightPosition(vec3(0.0f, 1000.0f, 0.0f));
	cylinder1.Draw(false);
	phong_shader.UnUse();

	cylinder1.UpdateValues(TestUpdate, window->LocalTime(), nullptr);
}
예제 #4
0
void setupSBA(SysSBA &sys)
{
    // Create camera parameters.
    frame_common::CamParams cam_params;
    cam_params.fx = 430; // Focal length in x
    cam_params.fy = 430; // Focal length in y
    cam_params.cx = 320; // X position of principal point
    cam_params.cy = 240; // Y position of principal point
    cam_params.tx = 0.3; // Baseline 

    // Define dimensions of the image.
    int maxx = 640;
    int maxy = 480;

    // Create a plane containing a wall of points.
    Plane middleplane;
    middleplane.resize(3, 2, 10, 5);
    //middleplane.rotate(PI/4.0, PI/6.0, 1, 0);
    middleplane.rotate(PI/4.0, 1, 0, 1);
    middleplane.translate(0.0, 0.0, 5.0);
    
    // Create another plane containing a wall of points.
    Plane mp2;
    mp2.resize(3, 2, 10, 5);
    mp2.rotate(0, 0, 0, 1);
    mp2.translate(0.0, 0.0, 4.0);


    // Create another plane containing a wall of points.
    Plane mp3;
    mp3.resize(3, 2, 10, 5);
    mp3.rotate(-PI/4.0, 1, 0, 1);
    mp3.translate(0.0, 0.0, 4.5);



    // Vector containing the true point positions.
    vector<Eigen::Vector3d, Eigen::aligned_allocator<Eigen::Vector3d> > normals;
    
    points.insert(points.end(), middleplane.points.begin(), middleplane.points.end());
    normals.insert(normals.end(), middleplane.points.size(), middleplane.normal);
    points.insert(points.end(), mp2.points.begin(), mp2.points.end());
    normals.insert(normals.end(), mp2.points.size(), mp2.normal);
    points.insert(points.end(), mp3.points.begin(), mp3.points.end());
    normals.insert(normals.end(), mp3.points.size(), mp3.normal);
    
    // Create nodes and add them to the system.
    unsigned int nnodes = 2; // Number of nodes.
    double path_length = 1.0; // Length of the path the nodes traverse.

    // Set the random seed.
    unsigned short seed = (unsigned short)time(NULL);
    seed48(&seed);
    
    unsigned int i = 0;
    
    Vector3d inormal0 = middleplane.normal;
    Vector3d inormal1 = middleplane.normal;
    Vector3d inormal20 = mp2.normal;
    Vector3d inormal21 = mp2.normal;
    Vector3d inormal30 = mp3.normal;
    Vector3d inormal31 = mp3.normal;
    
    for (i = 0; i < nnodes; i++)
    { 
      // Translate in the x direction over the node path.
      Vector4d trans(i/(nnodes-1.0)*path_length, 0, 0, 1);
            
#if 1
      if (i >= 2)
	    {
	      // perturb a little
	      double tnoise = 0.5;	// meters
	      trans.x() += tnoise*(drand48()-0.5);
	      trans.y() += tnoise*(drand48()-0.5);
	      trans.z() += tnoise*(drand48()-0.5);
	    }
#endif

      // Don't rotate.
      Quaterniond rot(1, 0, 0, 0);
#if 1
      if (i >= 2)
	    {
	      // perturb a little
	      double qnoise = 0.1;	// meters
	      rot.x() += qnoise*(drand48()-0.5);
	      rot.y() += qnoise*(drand48()-0.5);
	      rot.z() += qnoise*(drand48()-0.5);
	    }
#endif
      rot.normalize();
      
      // Add a new node to the system.
      sys.addNode(trans, rot, cam_params, false);
      
      // set normal
      if (i == 0)
	{
	  inormal0 = rot.toRotationMatrix().transpose() * inormal0;
	  inormal20 = rot.toRotationMatrix().transpose() * inormal20;
	  inormal30 = rot.toRotationMatrix().transpose() * inormal30;
	}
      else
	{
	  inormal1 = rot.toRotationMatrix().transpose() * inormal1;
	  inormal21 = rot.toRotationMatrix().transpose() * inormal21;
	  inormal31 = rot.toRotationMatrix().transpose() * inormal31;
	}
    }
        
    double pointnoise = 1.0;
    
    // Add points into the system, and add noise.
    for (i = 0; i < points.size(); i++)
    {
      // Add up to .5 points of noise.
      Vector4d temppoint = points[i];
      temppoint.x() += pointnoise*(drand48() - 0.5);
      temppoint.y() += pointnoise*(drand48() - 0.5);
      temppoint.z() += pointnoise*(drand48() - 0.5);
      sys.addPoint(temppoint);
    }
    
    // Each point gets added twice
    for (i = 0; i < points.size(); i++)
    {
      // Add up to .5 points of noise.
      Vector4d temppoint = points[i];
      temppoint.x() += pointnoise*(drand48() - 0.5);
      temppoint.y() += pointnoise*(drand48() - 0.5);
      temppoint.z() += pointnoise*(drand48() - 0.5);
      sys.addPoint(temppoint);
    }

    Vector2d proj2d, proj2dp;
    Vector3d proj, projp, pc, pcp, baseline, baselinep;
    
    Vector3d imagenormal(0, 0, 1);
    
    Matrix3d covar0;
    covar0 << sqrt(imagenormal(0)), 0, 0, 0, sqrt(imagenormal(1)), 0, 0, 0, sqrt(imagenormal(2));
    Matrix3d covar;
    
    Quaterniond rotation;
    Matrix3d rotmat;
    
    unsigned int midindex = middleplane.points.size();
    printf("Normal for Middle Plane: [%f %f %f], index %d -> %d\n", middleplane.normal.x(), middleplane.normal.y(), middleplane.normal.z(), 0, midindex-1);
    
    int nn = points.size();

    // Project points into nodes.
    for (i = 0; i < points.size(); i++)
    {
      int k=i;
      // Project the point into the node's image coordinate system.
      sys.nodes[0].setProjection();
      sys.nodes[0].project2im(proj2d, points[k]);
      sys.nodes[1].setProjection();
      sys.nodes[1].project2im(proj2dp, points[k]);
        
      // Camera coords for right camera
      baseline << sys.nodes[0].baseline, 0, 0;
      pc = sys.nodes[0].Kcam * (sys.nodes[0].w2n*points[k] - baseline); 
      proj.head<2>() = proj2d;
      proj(2) = pc(0)/pc(2);
        
      baseline << sys.nodes[1].baseline, 0, 0;
      pcp = sys.nodes[1].Kcam * (sys.nodes[1].w2n*points[k] - baseline); 
      projp.head<2>() = proj2dp;
      projp(2) = pcp(0)/pcp(2);

      // add noise to projections
      double prnoise = 0.5;	// 0.5 pixels
      proj.head<2>() += Vector2d(prnoise*(drand48() - 0.5),prnoise*(drand48() - 0.5));
      projp.head<2>() += Vector2d(prnoise*(drand48() - 0.5),prnoise*(drand48() - 0.5));


      // If valid (within the range of the image size), add the stereo 
      // projection to SBA.
      if (proj.x() > 0 && proj.x() < maxx && proj.y() > 0 && proj.y() < maxy)
        {
          // add point cloud shape-holding projections to each node
          sys.addStereoProj(0, k, proj);
          sys.addStereoProj(1, k+nn, projp);

#ifdef USE_PP
          // add exact matches
          if (i == 20 || i == 65 || i == 142)
            sys.addStereoProj(1, k, projp);
#endif

#ifdef USE_PPL
          // add point-plane matches
	  if (i < midindex)
            sys.addPointPlaneMatch(0, k, inormal0, 1, k+nn, inormal1);
	  else if (i < 2*midindex)
	    sys.addPointPlaneMatch(0, k, inormal20, 1, k+nn, inormal21);
	  else
	    sys.addPointPlaneMatch(0, k, inormal30, 1, k+nn, inormal31);
          //          sys.addStereoProj(0, k+nn, projp);
          //          sys.addStereoProj(1, k, proj);

          Matrix3d covar;
          double cv = 0.01;
          covar << cv, 0, 0,
            0, cv, 0, 
            0, 0, cv;
          sys.setProjCovariance(0, k+nn, covar);
          sys.setProjCovariance(1, k, covar);
#endif

        }
      else
        {
          cout << "ERROR! point not in view of nodes" << endl;
          //return;
        }
    }

    // Add noise to node position.
    
    double transscale = 2.0;
    double rotscale = 0.5;
    
    // Don't actually add noise to the first node, since it's fixed.
    for (i = 1; i < sys.nodes.size(); i++)
    {
      Vector4d temptrans = sys.nodes[i].trans;
      Quaterniond tempqrot = sys.nodes[i].qrot;
      
      // Add error to both translation and rotation.
      temptrans.x() += transscale*(drand48() - 0.5);
      temptrans.y() += transscale*(drand48() - 0.5);
      temptrans.z() += transscale*(drand48() - 0.5);
      tempqrot.x() += rotscale*(drand48() - 0.5);
      tempqrot.y() += rotscale*(drand48() - 0.5);
      tempqrot.z() += rotscale*(drand48() - 0.5);
      tempqrot.normalize();
      
      sys.nodes[i].trans = temptrans;
      sys.nodes[i].qrot = tempqrot;
      
      // These methods should be called to update the node.
      sys.nodes[i].normRot();
      sys.nodes[i].setTransform();
      sys.nodes[i].setProjection();
      sys.nodes[i].setDr(true);
    }
        
}
예제 #5
0
void Frustum::ExtractPlanes(glm::mat4 &clip)
{
	
        Plane *pPlane = 0;
		pPlane = &planes[FRUSTUM_PLANE_NEAR];
		pPlane->set(clip[0].w + clip[0].z, clip[1].w + clip[1].z, clip[2].w + clip[2].z, clip[3].w + clip[3].z);
        pPlane->normalize();

        // Left clipping plane.
        pPlane = &planes[FRUSTUM_PLANE_FAR];
        pPlane->set(clip[0].w - clip[0].z, clip[1].w - clip[1].z,clip[2].w - clip[2].z,clip[3].w - clip[3].z);
        pPlane->normalize();

        // Left clipping plane.
        pPlane = &planes[FRUSTUM_PLANE_LEFT];
        pPlane->set(clip[0].w + clip[0].x,clip[1].w + clip[1].x,clip[2].w + clip[2].x,clip[3].w + clip[3].x);
        pPlane->normalize();

        pPlane = &planes[FRUSTUM_PLANE_RIGHT];
        pPlane->set(clip[0].w - clip[0].x, clip[1].w - clip[1].x, clip[2].w - clip[2].x, clip[3].w - clip[3].x);
        pPlane->normalize();

        pPlane = &planes[FRUSTUM_PLANE_BOTTOM];
        pPlane->set(clip[0].w + clip[0].y,clip[1].w + clip[1].y,clip[2].w + clip[2].y,clip[3].w + clip[3].y);
        pPlane->normalize();

        pPlane = &planes[FRUSTUM_PLANE_TOP];
        pPlane->set(clip[0].w - clip[0].y, clip[1].w - clip[1].y, clip[2].w - clip[2].y, clip[3].w- clip[3].y);
        pPlane->normalize();
}
예제 #6
0
bool Ray::Intersects(const Plane &plane) const
{
	return plane.Intersects(*this, 0);
}
		void Frustum::ExtractPlanes(ScePspFMatrix4 &clip)
		{
			Plane *pPlane = 0;

			// Left clipping plane.
			/*pPlane = &planes[FRUSTUM_PLANE_NEAR];
			pPlane->set(clip.w.x + clip.z.x,clip.w.y + clip.z.y,clip.w.z + clip.z.z,clip.w.w + clip.z.w);
			pPlane->normalize();

			// Left clipping plane.
			pPlane = &planes[FRUSTUM_PLANE_FAR];
			pPlane->set(clip.w.x - clip.z.x,clip.w.y - clip.z.y,clip.w.z - clip.z.z,clip.w.w - clip.z.w);
			pPlane->normalize();

			// Left clipping plane.
			pPlane = &planes[FRUSTUM_PLANE_LEFT];
			pPlane->set(clip.w.x + clip.x.x,clip.w.y + clip.x.y,clip.w.z + clip.x.z,clip.w.w + clip.x.w);
			pPlane->normalize();

			pPlane = &planes[FRUSTUM_PLANE_RIGHT];
			pPlane->set(clip.w.x - clip.x.x,clip.w.y - clip.x.y,clip.w.z - clip.x.z,clip.w.w - clip.x.w);
			pPlane->normalize();

			pPlane = &planes[FRUSTUM_PLANE_BOTTOM];
			pPlane->set(clip.w.x + clip.y.x,clip.w.y + clip.y.y,clip.w.z + clip.y.z,clip.w.w + clip.y.w);
			pPlane->normalize();

			pPlane = &planes[FRUSTUM_PLANE_TOP];
			pPlane->set(clip.w.x - clip.y.x,clip.w.y - clip.y.y,clip.w.z - clip.y.z,clip.w.w - clip.y.w);
			pPlane->normalize();*/

			// Left clipping plane.
			pPlane = &planes[FRUSTUM_PLANE_NEAR];
			pPlane->set(clip.x.w + clip.x.z,clip.y.w + clip.y.z,clip.z.w + clip.z.z,clip.w.w + clip.w.z);
			pPlane->normalize();

			// Left clipping plane.
			pPlane = &planes[FRUSTUM_PLANE_FAR];
			pPlane->set(clip.x.w - clip.x.z,clip.y.w - clip.y.z,clip.z.w - clip.z.z,clip.w.w - clip.w.z);
			pPlane->normalize();

			// Left clipping plane.
			pPlane = &planes[FRUSTUM_PLANE_LEFT];
			pPlane->set(clip.x.w + clip.x.x,clip.y.w + clip.y.x,clip.z.w + clip.z.x,clip.w.w + clip.w.x);
			pPlane->normalize();

			pPlane = &planes[FRUSTUM_PLANE_RIGHT];
			pPlane->set(clip.x.w - clip.x.x,clip.y.w - clip.y.x,clip.z.w - clip.z.x,clip.w.w - clip.w.x);
			pPlane->normalize();

			pPlane = &planes[FRUSTUM_PLANE_BOTTOM];
			pPlane->set(clip.x.w + clip.x.y,clip.y.w + clip.y.y,clip.z.w + clip.z.y,clip.w.w + clip.w.y);
			pPlane->normalize();

			pPlane = &planes[FRUSTUM_PLANE_TOP];
			pPlane->set(clip.x.w - clip.x.y,clip.y.w - clip.y.y,clip.z.w - clip.z.y,clip.w.w - clip.w.y);
			pPlane->normalize();


		}
int loadSFM(char* fileName, Mesh &mesh) {
	fstream file(fileName);
	string buffer;

	vector<point3> vertices;
	vector<vec3>   normals;
	vector<point3> faces;


	// if not opened
	if (!file.is_open())
	{
		cout << "Unable to open file" << endl;
		return 0;
	}

	// read file line by line
	while (getline(file, buffer, '\n'))
	{
		//if (buffer[0] == 'v') {
		//	fprintf(stdout, "Got v\n");
		//}

		if (buffer[0] != 'v' && buffer[0] != 'f') {
			continue;
		}

		// read each element in this line
		stringstream currentLine(buffer);
		string currentColumn;
		vector<double> triangleElement;
		while (getline(currentLine, currentColumn, '\ '))
		{
			if (currentColumn[0] != 'v' && currentColumn[0] != 'f') {
				triangleElement.push_back(stod(currentColumn)); //! stod converts string to double
			}
		}

		if (triangleElement.size() != 3) {
			fprintf(stdout, "Only read %llu elements from current line \n", triangleElement.size());
			return 0;
		}


		if (buffer[0] == 'v') {
			vertices.push_back(point3(triangleElement[0], triangleElement[1], triangleElement[2]));
			normals.push_back(vec3(0.0));
		}
		else if (buffer[0] == 'f') {
			faces.push_back(point3(triangleElement[0], triangleElement[1], triangleElement[2]));
		}
		else {
			fprintf(stdout, "buffer[0] is not either 'v' or 'f' \n");
			return 0;
		}
		
		
	}


	averageNormals(vertices, faces, normals);


	Plane temp;

	// store data in mesh
	for (int i = 0; i < faces.size(); i++) {
		//! smf index starts from 1 instead of 0, so need to -1
		Triangle3D facet;

		facet.faces[0] = int(faces[i][0]) - 1;
		facet.faces[1] = int(faces[i][1]) - 1;
		facet.faces[2] = int(faces[i][2]) - 1;

		facet.vertices[0] = vertices[facet.faces[0]];
		facet.vertices[1] = vertices[facet.faces[1]];
		facet.vertices[2] = vertices[facet.faces[2]];

		facet.normals[0] = normals[facet.faces[0]];
		facet.normals[1] = normals[facet.faces[1]];
		facet.normals[2] = normals[facet.faces[2]];
	
		
		temp.set3Points(facet.vertices[0], facet.vertices[2], facet.vertices[1]); // in this case clock wise is normal direction

		facet.triangleNormal = temp.normal;
		facet.centerOfMass = (facet.vertices[0] + facet.vertices[1] + facet.vertices[2]) / 3;
		mesh.push_back(facet);
	}

	return 1;
}
예제 #9
0
파일: Lam.cpp 프로젝트: xxxAEKxxx/Seasons
//------------------------------------------------------------------
void CLam::UpdateTPLaser(float frameTime, CItem* parent)
{
	FUNCTION_PROFILER(GetISystem(), PROFILE_GAME);

	const int frameId = gEnv->pRenderer->GetFrameID();

	if (s_lastUpdateFrameId != frameId)
	{
		// Check how many LAMs to update this frame.
		float dt = frameTime; // + s_laserUpdateTimeError;

		const int n = s_lasers.size();

		int nActive = 0;
		for (int i = 0; i < n; ++i)
		{
			if (!s_lasers[i]->IsLaserActivated() && !s_lasers[i]->IsLightActivated())
				continue;
			nActive++;
		}

		float updatedPerSecond = (nActive / LASER_UPDATE_TIME) + s_laserUpdateTimeError;
		int updateCount = (int)floorf(updatedPerSecond * dt);
		if(dt==0.0f)
			s_laserUpdateTimeError = 0.0f;
		else
			s_laserUpdateTimeError = updatedPerSecond - updateCount/dt;

		s_curLaser %= n;
		for (int i = 0, j = 0; i < n && j < updateCount ; ++i)
		{
			s_curLaser = (s_curLaser + 1) % n;
			if (!s_lasers[s_curLaser]->IsLaserActivated() && !s_lasers[s_curLaser]->IsLightActivated())
				continue;
			s_lasers[s_curLaser]->SetAllowUpdate();
			++j;
		}

		s_lastUpdateFrameId = frameId;
	}

	IEntity* pRootEnt = GetEntity();
	if (!pRootEnt)
		return;

	IEntity *pLaserEntity = m_pEntitySystem->GetEntity(m_pLaserEntityId);
//	if(!pLaserEntity)
//		return;

	const CCamera& camera = gEnv->pRenderer->GetCamera();

	Vec3   lamPos = pRootEnt->GetWorldPos(); //pLaserEntity->GetParent()->GetWorldPos();
	Vec3   dir = pRootEnt->GetWorldRotation().GetColumn1(); //pLaserEntity->GetParent()->GetWorldRotation().GetColumn1();

	bool charNotVisible = false;

	float  dsg1Scale = 1.0f;

	//If character not visible, laser is not correctly updated
	if(parent)
	{
		if(CActor* pOwner = parent->GetOwnerActor())
		{
			ICharacterInstance* pCharacter = pOwner->GetEntity()->GetCharacter(0);
			if(pCharacter && !pCharacter->IsCharacterVisible())
				charNotVisible = true;
		}
		if(parent->GetEntity()->GetClass()==CItem::sDSG1Class)
			dsg1Scale = 3.0f;
	}
 
//	if (!pLaserEntity->GetParent())
//		return;

	Vec3 hitPos(0,0,0);
	float laserLength = 0.0f;

	// HACK??: Use player movement controller locations, or else the laser
	// pops all over the place when character out of the screen.
	CActor *pActor = parent->GetOwnerActor();
	if (pActor && (!pActor->IsPlayer() || charNotVisible))
	{
		if (IMovementController* pMC = pActor->GetMovementController())
		{
			SMovementState state;
			pMC->GetMovementState(state);
			if(!charNotVisible)
				lamPos = state.weaponPosition;
			else
			{
				float oldZPos = lamPos.z;
				lamPos = state.weaponPosition;
				if(m_lastZPos>0.0f)
					lamPos.z = m_lastZPos; //Stabilize somehow z position (even if not accurate)
				else
					lamPos.z = oldZPos;
			}
			const float angleMin = DEG2RAD(3.0f);
			const float angleMax = DEG2RAD(7.0f);
			const float thr = cosf(angleMax);
			float dot = dir.Dot(state.aimDirection);
			if (dot > thr)
			{
				float a = acos_tpl(dot);
				float u = 1.0f - clamp((a - angleMin) / (angleMax - angleMin), 0.0f, 1.0f);
				dir = dir + u * (state.aimDirection - dir);
				dir.Normalize();
			}
		}
	}

	if(!charNotVisible)
		m_lastZPos = lamPos.z;

	lamPos += (dir*0.10f);

	if (m_allowUpdate)
	{
		m_allowUpdate = false;

		IPhysicalEntity* pSkipEntity = NULL;
		if(parent->GetOwner())
			pSkipEntity = parent->GetOwner()->GetPhysics();

		const float range = m_lamparams.laser_range[eIGS_ThirdPerson]*dsg1Scale;

		// Use the same flags as the AI system uses for visbility.
		const int objects = ent_terrain|ent_static|ent_rigid|ent_sleeping_rigid|ent_independent; //ent_living;
		const int flags = (geom_colltype_ray << rwi_colltype_bit) | rwi_colltype_any | (10 & rwi_pierceability_mask) | (geom_colltype14 << rwi_colltype_bit);

		ray_hit hit;
		if (gEnv->pPhysicalWorld->RayWorldIntersection(lamPos, dir*range, objects, flags,
			&hit, 1, &pSkipEntity, pSkipEntity ? 1 : 0))
		{
			laserLength = hit.dist;
			m_lastLaserHitPt = hit.pt;
			m_lastLaserHitSolid = true;
		}
		else
		{
			m_lastLaserHitSolid = false;
			m_lastLaserHitPt = lamPos + dir * range;
			laserLength = range + 0.1f;
		}

		// Hit near plane
		if (dir.Dot(camera.GetViewdir()) < 0.0f)
		{
			Plane nearPlane;
			nearPlane.SetPlane(camera.GetViewdir(), camera.GetPosition());
			nearPlane.d -= camera.GetNearPlane()+0.15f;
			Ray ray(lamPos, dir);
			Vec3 out;
			m_lastLaserHitViewPlane = false;
			if (Intersect::Ray_Plane(ray, nearPlane, out))
			{
				float dist = Distance::Point_Point(lamPos, out);
				if (dist < laserLength)
				{
					laserLength = dist;
					m_lastLaserHitPt = out;
					m_lastLaserHitSolid = true;
					m_lastLaserHitViewPlane = true;
				}
			}
		}

		hitPos = m_lastLaserHitPt;
	}
	else
	{
		laserLength = Distance::Point_Point(m_lastLaserHitPt, lamPos);
		hitPos = lamPos + dir * laserLength;
	}

	if (m_smoothLaserLength < 0.0f)
		m_smoothLaserLength = laserLength;
	else
	{
		if (laserLength < m_smoothLaserLength)
			m_smoothLaserLength = laserLength;
		else
			m_smoothLaserLength += (laserLength - m_smoothLaserLength) * min(1.0f, 10.0f * frameTime);
	}

	float laserAIRange = 0.0f;
	if (m_laserActivated && pLaserEntity)
	{
		// Orient the laser towards the point point.
		Matrix34 parentTMInv;
		parentTMInv = pRootEnt->GetWorldTM().GetInverted();

		Vec3 localDir = parentTMInv.TransformPoint(hitPos);
		float finalLaserLen = localDir.NormalizeSafe();
		Matrix33 rot;
		rot.SetIdentity();
		rot.SetRotationVDir(localDir);
		pLaserEntity->SetLocalTM(rot);

		laserAIRange = finalLaserLen;

		const float assetLength = 2.0f;
		finalLaserLen = CLAMP(finalLaserLen,0.01f,m_lamparams.laser_max_len*dsg1Scale);
		float scale = finalLaserLen / assetLength; 

		// Scale the laser based on the distance.
		if (m_laserEffectSlot >= 0)
		{
			Matrix33 scl;
			scl.SetIdentity();
			scl.SetScale(Vec3(1,scale,1));
			pLaserEntity->SetSlotLocalTM(m_laserEffectSlot, scl);
		}

		if (m_dotEffectSlot >= 0)
		{
			if (m_lastLaserHitSolid)
			{
				Matrix34 mt = Matrix34::CreateTranslationMat(Vec3(0,finalLaserLen,0));
				if(m_lastLaserHitViewPlane)
					mt.Scale(Vec3(0.2f,0.2f,0.2f));
				pLaserEntity->SetSlotLocalTM(m_dotEffectSlot, mt);
			}
			else
			{
				Matrix34 scaleMatrix;
				scaleMatrix.SetIdentity();
				scaleMatrix.SetScale(Vec3(0.001f,0.001f,0.001f));
				pLaserEntity->SetSlotLocalTM(m_dotEffectSlot, scaleMatrix);
			}
		}
	}

	float lightAIRange = 0.0f;
	if (m_lightActivated)
	{
		float range = clamp(m_smoothLaserLength, 0.5f, m_lamparams.light_range[eIGS_ThirdPerson]);
		lightAIRange = range * 1.5f;

		if (m_lightID[eIGS_ThirdPerson] && m_smoothLaserLength > 0.0f)
		{
			CItem* pLightEffect = this;
			if (IItem *pOwnerItem = m_pItemSystem->GetItem(GetParentId()))
				pLightEffect = (CItem *)pOwnerItem;
			pLightEffect->SetLightRadius(range, m_lightID[eIGS_ThirdPerson]);
		}
	}


	if (laserAIRange > 0.0001f || lightAIRange > 0.0001f)
		UpdateAILightAndLaser(lamPos, dir, lightAIRange, m_lamparams.light_fov[eIGS_ThirdPerson], laserAIRange);

}
예제 #10
0
파일: plane.c 프로젝트: 10crimes/code
float V3d::distAbove(Plane p) { // -ve if below in terms of plane's normal
  return p.distto(*this);
}
예제 #11
0
파일: main.cpp 프로젝트: jellymann/shexp
int main(int argc, char** argv)
{
  GFXBoilerplate gfx(SCREEN_WIDTH, SCREEN_HEIGHT);
  gfx.init();
  glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS);

  ////////////// LOAD SH LUT //////////////

  Texture2d sh_lut, a_lut, b_lut, len_lut;

  ifstream in(argc > 1 ? argv[0] : "sh_lut.txt");
  if (!in)
  {
    cout << "Error loading file " << (argc > 1 ? argv[0] : "sh_lut.txt") << endl;
    return 1;
  }
  int lut_size;
  in >> lut_size;
  float* sh_logs = new float[lut_size*N_COEFFS];
  float* a_coeffs = new float[lut_size];
  float* b_coeffs = new float[lut_size];
  float* inv_lens = new float[lut_size];

  double tmp;
  for (int i = 0; i < lut_size*N_COEFFS; i++)
  {
    in >> tmp;
    sh_logs[i] = static_cast<float>(tmp);
  }
  for (int i = 0; i < lut_size; i++)
  {
    in >> tmp;
    a_coeffs[i] = static_cast<float>(tmp);
  }
  for (int i = 0; i < lut_size; i++)
  {
    in >> tmp;
    b_coeffs[i] = static_cast<float>(tmp);
  }

  const float MAX_ZH_LENGTH = 8.845128074703045f;

  float lengths[lut_size];
  for (int i = 0; i < lut_size; i++)
  {
    lengths[i] = sh_length(sh_logs+i*N_COEFFS)/MAX_ZH_LENGTH;
  }

  for (int i = 0; i < lut_size; i++)
  {
    float fx = (float)i/(float)lut_size;
    int j = 1;
    while (lengths[j] < fx && j < lut_size) j++;

    float u = unlerp(lengths[j-1], lengths[j], fx);

    float x = (float)j - 1.f + u;
    inv_lens[i] = x/(float)lut_size;
  }

  GLuint tex_offset = 0;

  glActiveTexture(GL_TEXTURE0+(tex_offset++));
  sh_lut.build();
  sh_lut.load_tex(sh_logs, N_COEFFS, lut_size, GL_R32F, GL_RED, GL_FLOAT);

  glActiveTexture(GL_TEXTURE0+(tex_offset++));
  a_lut.build();
  a_lut.load_tex(a_coeffs, 1, lut_size, GL_R32F, GL_RED, GL_FLOAT);

  glActiveTexture(GL_TEXTURE0+(tex_offset++));
  b_lut.build();
  b_lut.load_tex(b_coeffs, 1, lut_size, GL_R32F, GL_RED, GL_FLOAT);

  glActiveTexture(GL_TEXTURE0+(tex_offset++));
  len_lut.build();
  len_lut.load_tex(inv_lens, 1, lut_size, GL_R32F, GL_RED, GL_FLOAT);

  delete [] sh_logs;
  delete [] a_coeffs;
  delete [] b_coeffs;
  delete [] inv_lens;

  ////////////// GENERATE LH CUBEMAPS ////////////

  const int SQRT_N_SAMPLES = 100;
  const int N_SAMPLES = SQRT_N_SAMPLES*SQRT_N_SAMPLES;
  SHSample* samples = new SHSample[N_SAMPLES];
  for (int i = 0; i < N_SAMPLES; i++)
  {
    samples[i].coeff = new double[N_COEFFS];
  }
  SH_setup_spherical_samples(samples, SQRT_N_SAMPLES, N_BANDS);

  double *l_coeff = new double[N_COEFFS];
  double *h_coeff = new double[N_COEFFS];

  auto sky_function = clearsky(M_PI*0.3, M_PI);

  SH_project_polar_function(sky_function, samples, N_SAMPLES, N_BANDS, l_coeff);

  const int H_MAP_SIZE = 8;

  auto h_map_function = [l_coeff, h_coeff, samples](double theta, double phi, double *coeffs)
  {
    SH_project_polar_function(h_function(theta, phi), samples, N_SAMPLES, N_BANDS, h_coeff);

    for (int h = 0; h < N_COEFFS; h++)
    {
      h_coeff[h] /= M_PI;
    }

    SH_product(h_coeff, l_coeff, coeffs);
  };

  cout << "Loading H map ... " << endl;
  glActiveTexture(GL_TEXTURE0+(tex_offset++));
  CubeMapArray h_map_array = gen_sh_cube_map_array(H_MAP_SIZE, h_map_function,
      GL_R32F, GL_RED, GL_FLOAT);
  cout << "done." << endl;

  delete [] l_coeff;
  delete [] h_coeff;


  ///////////////// MAKE SPHERE ... DATA? ////////////////

  float *radiuses_data = new float[MAX_SPHERES];
  float *positions_data = new float[MAX_SPHERES*3];

  ///////////////// DO THE OPENGL THING ////////////////

  glfwSetCursorPosCallback(gfx.window(), mouse_callback);
  glfwSetKeyCallback(gfx.window(), my_key_callback);

  Shader* pos_shader = (new Shader())
    ->vertex("simple_vert.glsl")
    ->fragment("pos_frag.glsl")
    -> build();

  Shader* shexp_shader = (new Shader())
    ->vertex("pass_vert.glsl")
    ->fragment("shexp_frag.glsl")
    ->build();

  Shader* sh_shader = (new Shader())
    ->vertex("simple_vert.glsl")
    ->fragment("sh_frag.glsl")
    ->build();

  Shader* main_shader = (new Shader())
    ->vertex("simple_vert.glsl")
    ->fragment("main_frag.glsl")
    ->build();

  Shader* pp_shader = (new Shader())
    ->vertex("pass_vert.glsl")
    ->fragment("pp_pass.glsl")
    ->build();

  Shader* skybox = (new Shader())
    ->vertex("skybox_vert.glsl")
    ->fragment("skybox_frag.glsl")
    ->build();

  GLsizei buf_width = SCREEN_WIDTH/SCALE_DOWN_FACTOR;
  GLsizei buf_height = SCREEN_HEIGHT/SCALE_DOWN_FACTOR;

  glActiveTexture(GL_TEXTURE0+33);
  Texture2d pos_texture;
  pos_texture.build();
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
  pos_texture.load_tex(NULL, buf_width, buf_height,
      GL_RGB32F, GL_RGB, GL_FLOAT);

  glActiveTexture(GL_TEXTURE0+34);
  Texture2d norm_texture;
  norm_texture.build();
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
  norm_texture.load_tex(NULL, buf_width, buf_height,
      GL_RGB32F, GL_RGB, GL_FLOAT);

  Framebuffer pos_buffer(buf_width,buf_height);
  pos_buffer.build();

  pos_buffer.bind_to_texture(GL_COLOR_ATTACHMENT0,
      pos_texture.handle());
  pos_buffer.bind_to_texture(GL_COLOR_ATTACHMENT1,
      norm_texture.handle());

  glActiveTexture(GL_TEXTURE0+35);
  Texture2dArray sh_texture;
  sh_texture.build();
  sh_texture.load_tex(NULL, buf_width, buf_height, N_COEFFS/4,
      GL_RGBA32F, GL_RGBA, GL_FLOAT);
  Framebuffer sh_buffer(buf_width,buf_height);
  sh_buffer.build();
  for (int i = 0; i < N_COEFFS/4; i++)
  {
    sh_buffer.bind_to_texture_layer(GL_COLOR_ATTACHMENT0+i,
        sh_texture.handle(), i);
  }

  glActiveTexture(GL_TEXTURE0+36);
  Texture2d shexp_texture;
  shexp_texture.build();
  shexp_texture.load_tex(NULL, buf_width, buf_height,
      GL_R32F, GL_RED, GL_FLOAT);
  Framebuffer shexp_buffer(buf_width,buf_height);
  shexp_buffer.build();
  shexp_buffer.bind_to_texture(GL_COLOR_ATTACHMENT0,
      shexp_texture.handle());

  Sphere sph;
  sph.build();

  glActiveTexture(GL_TEXTURE0+42);
  CubeMap skymap = gen_cube_map(256, sky_function, GL_R32F, GL_RED, GL_FLOAT);

  NDCQuad all_the_pixels;
  all_the_pixels.build();

  int num_spheres = load_spheres("Humanoid_0000.vsp", positions_data,
      radiuses_data);

  Plane pln;
  pln.build();
  Transform plane_transform(vec3(0,0,0),quat(1,0,0,0),vec3(2000));
  WorldObject pln_obj(&pln, &plane_transform);

  WavefrontMesh dude("Humanoid_0000.obj");
  dude.build();
  Transform dude_transform(vec3(0,0,0), quat(1,0,0,0), vec3(1));
  WorldObject dude_obj(&dude, &dude_transform);

  GLsizei n_objects = 2;
  WorldObject** objects = new WorldObject*[n_objects];
  objects[0] = &pln_obj;
  objects[1] = &dude_obj;

  float oracle_factor = 15;
  float far = 2000.0f;
  int width, height;
  float aspect;
  mat4 projection;

  sh_shader->use();
  sh_shader->updateInt("screen_width", buf_width);
  sh_shader->updateInt("screen_height", buf_height);
  sh_shader->updateInt("position", 33);
  sh_shader->updateInt("normal", 34);
  sh_shader->updateFloat("oracle_factor", oracle_factor);
  sh_shader->updateInt("sh_lut", 0);

  shexp_shader->use();
  shexp_shader->updateInt("screen_width", buf_width);
  shexp_shader->updateInt("screen_height", buf_height);
  shexp_shader->updateInt("a_lut", 1);
  shexp_shader->updateInt("b_lut", 2);
  shexp_shader->updateInt("len_lut", 3);
  shexp_shader->updateInt("h_maps", 4);
  shexp_shader->updateFloat("max_zh_len", MAX_ZH_LENGTH);
  shexp_shader->updateInt("normal", 34);
  shexp_shader->updateInt("shlogs", 35);

  main_shader->use();
  main_shader->updateInt("shexps", 36);
  main_shader->updateInt("screen_width", buf_width);
  main_shader->updateInt("screen_height", buf_height);

  skybox->use();
  skybox->updateInt("map", 42);

  pp_shader->use();
  pp_shader->updateInt("tex1", 35);
  pp_shader->updateInt("tex2", 36);

  glEnable(GL_DEPTH_TEST);
  while (!glfwWindowShouldClose(gfx.window()))
  {
    glfwGetFramebufferSize(gfx.window(), &width, &height);

    aspect = (float)width/(float)height;
    projection = perspective(45.0f, aspect, 0.5f, far);

    handleInput(gfx.window());


    pos_buffer.use(2);

    pos_shader->use();
    pos_shader->updateMat4("view", camera.getView());
    pos_shader->updateMat4("projection", projection);

    draw_scene(pos_shader, objects, n_objects);


    sh_buffer.use(N_COEFFS/4);

    sh_shader->use();
    sh_shader->updateMat4("view", camera.getView());
    sh_shader->updateMat4("projection", projection);

    glDisable(GL_DEPTH_TEST);
    glEnable(GL_BLEND);
    glBlendEquation(GL_FUNC_ADD);
    glBlendFunc(GL_ONE, GL_ONE);

    splat_spheres(sh_shader, positions_data, radiuses_data, num_spheres,
        oracle_factor, &sph);

    glDisable(GL_BLEND);
    glEnable(GL_DEPTH_TEST);


    shexp_buffer.use(1);

    shexp_shader->use();

    all_the_pixels.draw();


    Framebuffer::unbind();

    glViewport(0, 0, width, height);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    skybox->use();
    skybox->updateFloat("aspect", aspect);
    skybox->updateMat4("view", camera.getView());
    skybox->updateMat4("projection", projection);

    glDepthMask(GL_FALSE);
    all_the_pixels.draw();
    glDepthMask(GL_TRUE);

    main_shader->use();
    main_shader->updateInt("screen_width", width);
    main_shader->updateInt("screen_height", height);
    main_shader->updateMat4("view", camera.getView());
    main_shader->updateMat4("projection", projection);

    draw_scene(main_shader, objects, n_objects);

    //pp_shader->use();
    //pp_shader->updateInt("screen_width", width);
    //pp_shader->updateInt("screen_height", height);

    //all_the_pixels.draw();

    glfwSwapBuffers(gfx.window());
    glfwPollEvents();
  }

  sph.destroy();
  pln.destroy();
  dude.destroy();

  sh_shader->destroy();
  shexp_shader->destroy();
  skybox->destroy();
  pos_shader->destroy();
  main_shader->destroy();
  delete sh_shader;
  delete shexp_shader;
  delete skybox;
  delete pos_shader;
  delete main_shader;

  delete [] positions_data;
  delete [] radiuses_data;
  delete [] objects;

  gfx.cleanup();

  return 0;
}
예제 #12
0
void thrust_HiForest(Int_t startfile = 0,
		     Int_t endfile = 1,
		     Int_t radius = 3,
		     std::string kFoname="test_output.root",
		     float ptCut = 30.0,
		     float etaCut = 2.0){

  TH1::SetDefaultSumw2();

  TStopwatch timer;
  bool debug = false;
  //Float_t pT_cut = 30;
  //Int_t radius = 3;
  
  //define trees and file
  TFile * file; 
  //TFile * weight_file;
  TTree * t;
  TTree * hiEvt;
  //TTree * hlt;
  TTree * skim;
  //TTree * weight;
  TTree * thrust_tree;

  /*
  //set up the tree to be filled
  thrust_tree->Branch("pthatweight",&pthatweight,"pthatweight/D");
  thrust_tree->Branch("hiBin",&hiBin,"hiBin/I");
  thrust_tree->Branch("evt",&evnt,"evt/I");
  thrust_tree->Branch("lumi",&lumi,"lumi/I");
  thrust_tree->Branch("vz",&vz,"vz/F");
  */


  //Tree variables
  Float_t pt[1000];    Int_t jt80;   Int_t jt80_pre;
  Float_t eta[1000];   Int_t jt40;   Int_t jt60_pre;
  Float_t phi[1000];   Int_t jt60;   Int_t jt40_pre;


  // Double_t px[1000];
  // Double_t py[1000];
  // Double_t pz[1000];
  
  Int_t nref;
  Float_t vz;
  Int_t hiBin;
  Int_t halo;
  Int_t noise;
  //Double_t pThat_weight;
  //Float_t pThat; 

  Float_t dot = 0;
  Double_t mag = 0;
  Double_t thrust_temp = 0;
  Double_t thrust_max = 0;
  Double_t dot_maj = 0;
  Double_t dot_min = 0;
  Double_t min_temp = 0;
  Double_t maj_temp = 0;
  Double_t thrust_maj_max =0;
  Double_t thrust_min_max = 0;
  TVector3 max_thrust_axis;
  TVector3 p3Norm;
  //Float_t max_eta = 0;   Float_t temp_eta = 0;  
  //Float_t max_phi = 0;   Float_t temp_phi = 0;
  Int_t max_nref;
  Int_t jetCount = 0; //in order to sum up the number of jets per event
  Int_t eventCount = 0;//check to see how many of the events in each file are actually being used

  //define instream
  string input_file = "jetRAA_PbPb_data_forest.txt"; 
  ifstream count(input_file.c_str(), ifstream::in);
  Int_t fileCount = 0;
  string * filename = new string[10000];

  //count up the total number of files and save their names to an array of filenames for initialization purposes
  
  string line;
  while(getline(count, line)){
    filename[fileCount] = line;
    if (debug) cout << filename[fileCount] << endl; 
    fileCount++;
  }
  count.close();

  
  TFile * save_File = new TFile(kFoname.c_str(),"RECREATE");

  TH1F * h_thrust[nbins_cent], * h_min[nbins_cent], * h_maj[nbins_cent], * h_pT[nbins_cent], * h_pTcut[nbins_cent], * h_nref[nbins_cent],
    * h_jetCount[nbins_cent], * h_eta[nbins_cent], * h_phi[nbins_cent], * h_TBad[nbins_cent],
    * h_TminBad[nbins_cent], * h_TmajBad[nbins_cent], * h_TBadpT[nbins_cent],
    * h_TmajBadpT[nbins_cent],* h_TminBadpT[nbins_cent], * h_etaBad[nbins_cent], * h_phiBad[nbins_cent], * h_nrefBad[nbins_cent], * h_jetCountBad[nbins_cent];

  //TH1F * h_weight = new TH1F("weighting", "", 500, 0, 500);
  //TH1F * h_weightBad = new TH1F("weightingBad", "", 500, 0, 500);
  //TH1F * h_pthatBad = new TH1F("pthatBad", "", 500, 0, 500);
  TH1F * h_fileNum = new TH1F("fileNum", "", 45, 0, 45);

  TH2F * hThrust_vs_Aj[nbins_cent];


  for(int i = 0; i<nbins_cent; ++i){

    hThrust_vs_Aj[i] = new TH2F(Form("hThrust_vs_Aj_cent%d",i),"",50, 0, 1, 50, 0, 1);
    h_thrust[i] = new TH1F(Form("thrust_unscaled_cent%d",i), "", 50,0,1);
    h_min[i] = new TH1F(Form("thrust_min_cent%d",i), "", 50,0,1);
    h_maj[i] = new TH1F(Form("thrust_maj_cent%d",i), "", 50,0,1);
    h_pT[i] = new TH1F(Form("pT_cent%d",i), "", 100, 0, 120);
    h_pTcut[i] = new TH1F(Form("pTcut_cent%d",i), "", 100, 0, 120);
    //h_40[i] = new TH1F(Form("thrust_40_cent%d",i), "", 50,0,1);
    //h_60[i] = new TH1F(Form("thrust_60_cent%d",i), "", 50,0,1);
    //h_80[i] = new TH1F(Form("thrust_80_cent%d",i), "", 50,0,1);
    h_nref[i] = new TH1F(Form("nref_cent%d",i), "", 12, 0, 12);
    h_jetCount[i] = new TH1F(Form("jetCount_cent%d",i), "", 12, 0, 12);
    h_eta[i] = new TH1F(Form("eta_cent%d",i), "", 60, -2, 2);
    h_phi[i] = new TH1F(Form("phi_cent%d",i), "", 60, -3.15, 3.15);
  
    h_TBad[i] = new TH1F(Form("thrust_bad_cent%d",i), "", 50,0,1);
    h_TminBad[i] = new TH1F(Form("thrust_min_bad_cent%d",i), "", 50,0,1);
    h_TmajBad[i] = new TH1F(Form("thrust_maj_bad_cent%d",i), "", 50,0,1);
    h_TBadpT[i] = new TH1F(Form("TBadpT_cent%d",i), "", 100, 0, 120);
    h_TmajBadpT[i] = new TH1F(Form("TmajBadpT_cent%d",i), "", 100, 0, 120);
    h_TminBadpT[i] = new TH1F(Form("TminBadpT_cent%d",i), "", 100, 0, 120);
    h_etaBad[i] = new TH1F(Form("etaBad_cent%d",i), "", 60, -2, 2);
    h_phiBad[i] = new TH1F(Form("phiBad_cent%d",i), "", 60, -3.15, 3.15);
    h_nrefBad[i] = new TH1F(Form("nrefBad_cent%d",i), "", 12, 0, 12);
    h_jetCountBad[i] = new TH1F(Form("jetCountBad_cent%d",i), "", 12, 0, 12);
  }
  
  // For every file in file list, process trees
  for(int ifile = startfile; ifile < endfile; ifile++){

    string s = filename[ifile];
    //string w = Form("weights_pbpb_%d.root", ifile+1); 
    file = TFile::Open(s.c_str());
    //weight_file = TFile::Open(w.c_str());

    if (debug) cout << "\n **** =========================== New File ================================= **** \n ";
    cout << "File Name: " << filename[ifile] << endl; 
    cout << "File Number: " << endfile-ifile << "/" << endfile-startfile << endl;
    //cout << "Weight File: " << w << endl;

    //define trees and file
    t = (TTree*)file->Get(Form("akPu%dPFJetAnalyzer/t", radius));
    hiEvt = (TTree*)file->Get("hiEvtAnalyzer/HiTree");
    //hlt = (TTree*)file->Get("hltanalysis/HltTree");
    skim = (TTree*)file->Get("skimanalysis/HltTree");
    //weight = (TTree*)weight_file->Get("weights");
    
    //Set branches of the tree 
    t->SetBranchAddress("jtpt", &pt);
    t->SetBranchAddress("jteta", &eta);
    t->SetBranchAddress("jtphi", &phi);
    t->SetBranchAddress("nref", &nref);
    //t->SetBranchAddress("pthat", &pThat);

    hiEvt->SetBranchAddress("vz", &vz);
    hiEvt->SetBranchAddress("hiBin", &hiBin);

    skim->SetBranchAddress("pHBHENoiseFilter", &noise);
    skim->SetBranchAddress("pcollisionEventSelection",&halo);
  
    //hlt->SetBranchAddress("HLT_PAJet80_NoJetID_v1",&jt80);
    //hlt->SetBranchAddress("HLT_PAJet60_NoJetID_v1",&jt60);
    //hlt->SetBranchAddress("HLT_PAJet40_NoJetID_v1",&jt40);
    //hlt->SetBranchAddress("HLT_PAJet80_NoJetID_v1_Prescl",&jt80_pre);
    //hlt->SetBranchAddress("HLT_PAJet60_NoJetID_v1_Prescl",&jt60_pre);
    //hlt->SetBranchAddress("HLT_PAJet40_NoJetID_v1_Prescl",&jt40_pre);

    //weight->SetBranchAddress("pthatweight", &pThat_weight);

    t->AddFriend(hiEvt);
    t->AddFriend(skim);
    //t->AddFriend(hlt);
    //t->AddFriend(weight);
    
    Long64_t nentries = t->GetEntries();
    //nentries = 10000;
    
    cout << "Events in File: " << nentries << endl;
    eventCount = 0;

    save_File->cd();
    
    //event loop
    for(Long64_t nentry = 0; nentry<nentries; ++nentry){
      //for(Long64_t nentry = 6662; nentry<6663; ++nentry){
      
      if(nentry%10000 == 0) cout << nentry << endl;
      
      t->GetEntry(nentry);
      skim->GetEntry(nentry);
      hiEvt->GetEntry(nentry);
      //weight->GetEntry(nentry);

      int cBin = findBin(hiBin);//tells us the centrality of the event. 
      if(cBin==-1 || cBin==nbins_cent) continue;
      
      jetCount = 0;
      bool select = false;

      //make selection cuts
      if(TMath::Abs(vz) > 15 || halo == 0 || noise == 0) continue;

      // apply the pT dijet clean sample selection
      if(pt[0]< 120 || pt[1] <50) continue; 
      
      //fill pThat spectra plot
      //h_weight->Fill(pThat, pThat_weight); 
      
      //if((TMath::Abs(vz) > 15)) {continue;}

      // get the pt vector for each event which passes you jet selections based on pT and eta
      vector <float> pt_v;
      vector <float> eta_v;
      vector <float> phi_v;

      for(int ij = 0; ij<nref; ++ij){

	if(pt[ij] > ptCut && fabs(eta[ij]) < etaCut){
	  pt_v.push_back(pt[ij]);	
	  eta_v.push_back(eta[ij]);	
	  phi_v.push_back(phi[ij]);
	}
      }

      if (debug) cout<<"Total Number of Jets    : "<<nref<<endl;
      if (debug) cout<<"Number of Selected Jets : "<<pt_v.size()<<endl;

      int NJets_Sel = pt_v.size();

      if(NJets_Sel < 2) {
	if (debug) cout<<"This event had only 1 Jet"<<endl;
	continue;	
      }

      double Aj = (double)(pt_v[0] - pt_v[1])/(pt_v[0]+pt_v[1]);
      
      // //intial pT cut
      // for(int k = 0; k < nref; k++){
      // 	if(pt[k] >  30){
      // 	  if((TMath::Abs(eta[k])<2)) select = true; 
      // 	}
      // }

      // if(!select) continue;
      if(debug) cout<< " \n ******* New Event ******** " << endl;
      if(debug) cout<< " ******* " << nentry << " ******** " << endl;
      
      //reset maximum values
      eventCount++;
      thrust_max = 0;

      vector <double> px;
      vector <double> py;
      vector <double> pz;
      
      for(Long64_t naxis = 0; naxis < NJets_Sel; ++naxis){
	float axis_jet_pt = pt_v[naxis];
	float axis_jet_eta = eta_v[naxis];
	float axis_jet_phi = phi_v[naxis];
      	px.push_back((double)axis_jet_pt * TMath::Cos(axis_jet_phi));
	py.push_back((double)axis_jet_pt * TMath::Sin(axis_jet_phi));
	pz.push_back((double)axis_jet_pt * TMath::SinH(axis_jet_eta));

	if(py[naxis] == 0) {
	  if(debug) cout << "PYZERO" << endl; 
	  if(debug) cout<< "Jet Variables: "<< "\n \t pT = "<<axis_jet_pt<<"\n \t eta = "<<axis_jet_eta<<"\n \t phi = "<<axis_jet_phi<<endl;

	}
      }

      //PART 1 ====================================================
      //Runs through all the jets in an event, checking them to see if they are the axis that maximizes thrust
      //max axis finding loop
      for(Long64_t naxis = 0; naxis < NJets_Sel; ++naxis){

	float axis_jet_pt = pt_v[naxis];
	float axis_jet_eta = eta_v[naxis];
	float axis_jet_phi = phi_v[naxis];
	
	//Cut checks
	//if(debug) cout<< "Jet Variables: "<< "\n \t pT = "<<axis_jet_pt<<"\n \t eta = "<<axis_jet_eta<<"\n \t phi = "<<axis_jet_phi<<endl;
	// h_pT->Fill(pt[naxis]);

	// if((pt[naxis] < pT_cut)||(TMath::Abs(eta[naxis]) > 2)) {
	//   continue;
	// }
	h_pTcut[cBin]->Fill(axis_jet_pt);
	
	// jetCount++; 
	
	if(debug) cout<< " \n --------- New Test Axis (Thrust)--------- " << endl; 
	
	//reset values for this particular event
	thrust_temp = 0;  // maj_temp = 0;   min_temp = 0;
	
	// px[naxis] = pt[naxis]*TMath::Cos(phi[naxis]);
	// py[naxis] = pt[naxis]*TMath::Sin(phi[naxis]);
	// pz[naxis] = pt[naxis]*TMath::SinH(eta[naxis]);
	
	//calculates axis for this particular jet
	TVector3 nT (px[naxis], py[naxis], pz[naxis]);
	if(debug) cout<<"Test Axis Unnormed = {" << nT(0) << ", " << nT(1) << ", " << nT(2)<< "}" << endl;
	nT = Norm(nT);
	
	if(debug) cout<<"Test Axis = {" << nT(0) << ", " << nT(1) << ", " << nT(2)<< "}" << endl;
	//temp_phi = axis_jet_phi;   temp_eta = axis_jet_eta;
	
	//resets for next jet loop
	dot = 0;   mag = 0;

	//PART 2 ====================================================
	//Loops through all the jets to find the thrust value for the chosen axis 
	//jet loop
	for(Long64_t njet = 0; njet < NJets_Sel; ++njet){
	  
	  // if((pt[njet] < pT_cut)||(TMath::Abs(eta[njet]) > 2)){ continue;}
	  float jet_pt = pt_v[njet];
	  float jet_eta = eta_v[njet];
	  float jet_phi = phi_v[njet];
	
	  if(debug) cout<< " \n --------- New Jet (Thrust)--------- " << endl; 
	  if(debug) cout<< "Jet Variables: "<< "\n \t pT = "<<jet_pt<<"\n \t eta = "<<jet_eta<<"\n \t phi = "<<jet_phi<<endl;
	  
	  //calculate px, py, pz
	  // px[njet] = pt[njet]*TMath::Cos(phi[njet]);
	  // py[njet] = pt[njet]*TMath::Sin(phi[njet]); 
	  // pz[njet] = pt[njet]*TMath::SinH(eta[njet]);
	
	  //define momentum three vector
	  TVector3 p3 (px[njet], py[njet], pz[njet]);
	  //TVector3 p3Norm = Norm(p3);
	  
	  if(debug) cout<<"Jet Axis = {" << p3(0) << ", " << p3(1) << ", " << p3(2)<< "}" << endl;
	  
	  //dots the two vectors for Thrust, Tmin and Tmaj
	  dot += TMath::Abs(p3.Dot(nT)); 
	  if(debug) cout<<"dot sum = " << dot << endl;
	  
	  //sum the total p from the individual p magnitudes
	  mag += TMath::Abs(p3.Mag());
	  if(debug) cout<<"mag sum = " << mag << endl;
	  
	}//end jet loop
	
	//calculate the thrust
	thrust_temp = ((dot)/mag);
	
	//Compare to see if this axis is a new maximum 
	if(debug) cout<< "\ntemp thrust = " << thrust_temp << endl; 
	
	if(thrust_temp>thrust_max){
	  thrust_max = thrust_temp;
	  max_thrust_axis = nT;
	  //max_eta = temp_eta;
	  //max_phi = temp_phi;
	  max_nref = naxis;
	  
	}
	if(debug) cout<< "max thrust = " << thrust_max << endl;
	
      }//end axis loop
      
      if (debug) cout << "FINAL THRUST VALUE: " << thrust_max << endl; 
      
      // FILL BAD THRUST VALUES TO DEBUG =============================
      if(thrust_max < 0.47) {
	
	//h_TBadpT->Fill(pt[naxis], pThat_weight);
	h_TBad[cBin]->Fill(thrust_max);
	h_etaBad[cBin]->Fill(eta_v[max_nref]);
	h_phiBad[cBin]->Fill(phi_v[max_nref]);
	h_nrefBad[cBin]->Fill(max_nref);
	h_jetCountBad[cBin]->Fill(NJets_Sel);
	//h_weightBad->Fill(pThat_weight);
	//h_pthatBad->Fill(pThat);
	h_fileNum->Fill(ifile);

	if (debug) cout << "______________________________" << endl; 
	if (debug) cout << "| X0X : THRUST LESS THAN 0.5 |" << endl;
	if (debug) cout << "|  Max Thrust: " << thrust_max << endl;
	//cout << "|  Max Thrust: " << thrust_max << endl;
	if (debug) cout << "______________________________" << endl; 
      }

      // fill thrust vs Aj plot
      hThrust_vs_Aj[cBin]->Fill(Aj, thrust_max);

    
      //PART 3 ====================================================
      //Begin code to select the Thrust Major and Minor axes
      
      //define the plane perpendicular to this axis in order to calculate Tmaj and Tmin
      Plane* perp = new Plane(max_thrust_axis);
      
      //reset maximum values for new axis test
      thrust_maj_max = 0;   thrust_min_max = 0; 
      
      //Thrust maj axis loop
      for(Long64_t naxis = 0; naxis < NJets_Sel; ++naxis){

	// if((pt[naxis] < pT_cut)||(TMath::Abs(eta[naxis]) > 2)){ continue;}
	if(debug) cout<< " \n --------- New Test Axis (Min/Maj)--------- " << endl; 
	
	//define the jet axis for this iteration
	//calculate px, py, pz
	// px[naxis] = pt[naxis]*TMath::Cos(phi[naxis]);
	// py[naxis] = pt[naxis]*TMath::Sin(phi[naxis]); 
	// pz[naxis] = pt[naxis]*TMath::SinH(eta[naxis]);
	
	//define momentum three vector
	TVector3 p3 (px[naxis], py[naxis], pz[naxis]);
	if(debug) cout<<"Jet Axis UnNormed = {" << p3(0) << ", " << p3(1) << ", " << p3(2)<< "}" << endl;
	p3 = Norm(p3);
	if(debug) cout<<"Jet Axis Normed = {" << p3(0) << ", " << p3(1) << ", " << p3(2)<< "}" << endl;
	
	//define maj_axis and min_axis 
	TVector3 maj_axis = perp->Projection((p3));
	if(debug) cout<<"Maj Axis UnNormed = {" << maj_axis(0) << ", " << maj_axis(1) << ", " << maj_axis(2)<< "}" << endl;
	maj_axis = Norm(maj_axis);
	TVector3 min_axis = max_thrust_axis.Cross(maj_axis);
	min_axis = Norm(min_axis); 
	
	if(debug) cout<<"Jet Axis = {" << p3(0) << ", " << p3(1) << ", " << p3(2)<< "}" << endl;
	if(debug) cout<<"Maj Axis = {" << maj_axis(0) << ", " << maj_axis(1) << ", " << maj_axis(2)<< "}" << endl;
	if(debug) cout<<"Min Axis = {" << min_axis(0) << ", " << min_axis(1) << ", " << min_axis(2)<< "}\n" << endl;
	
	//reset for new axis test
	dot_maj = 0;   dot_min = 0;   mag = 0;

	//PART 4 ====================================================
	//Test the axis defined by the above loop to determine if this axis is the maximum
	//jet loop
	for(Long64_t njet = 0; njet < NJets_Sel; ++njet){
	  
	  //make a ptcut
	  // if((pt[njet] < pT_cut)||(TMath::Abs(eta[njet]) > 2)){ continue;}
	  float jet_pt = pt_v[njet];
	  float jet_eta = eta_v[njet];
	  float jet_phi = phi_v[njet];
	  
	  if(debug) cout<< " \n --------- New Jet (Maj/Min)--------- " << endl; 
	  //if(debug) cout<< "Jet Variables: "<< "\n \t pT = "<<pt[njet]<<"\n \t eta = "<<eta[njet]<<"\n \t phi = "<<phi[njet]<<endl;
	  if(debug) cout<< "Jet Variables: "<< "\n \t pT = "<<jet_pt<<"\n \t eta = "<<jet_eta<<"\n \t phi = "<<jet_phi<<endl;

	  //calculate px, py, pz
	  // px[njet] = pt[njet]*TMath::Cos(phi[njet]);
	  // py[njet] = pt[njet]*TMath::Sin(phi[njet]); 
	  // pz[njet] = pt[njet]*TMath::SinH(eta[njet]);
	  
	  //define momentum three vector
	  TVector3 p3 (px[njet], py[njet], pz[njet]);
	  TVector3 p3Norm = Norm(p3);
	  
	  if(debug) cout<<"Jet Axis = {" << p3(0) << ", " << p3(1) << ", " << p3(2)<< "}" << endl;
	  
	  //dots the two vectors for Tmin and Tmaj
	  dot_maj += TMath::Abs(p3.Dot(maj_axis)); 
	  dot_min += TMath::Abs(p3.Dot(min_axis));
	  if(debug) cout<<"dot maj sum = " << dot_maj << endl;
	  if(debug) cout<<"dot min sum = " << dot_min << endl;
	  
	  //sum the total p from the individual p magnitudes
	  mag += TMath::Abs(p3.Mag());
	  if(debug) cout<<"mag sum = " << mag << endl;
	  
	}//end jet loop

	//calculate the thrust major and minor for this axis
	maj_temp = dot_maj/mag;
	min_temp = dot_min/mag;
	
	//test to to see if this particular Tmaj and Tmin are the new maxima
	if(maj_temp>thrust_maj_max){
	  thrust_maj_max = maj_temp;  
	  thrust_min_max = min_temp; 
	  if(debug) cout << "thrust major max = "<< thrust_maj_max<< endl;
	  /*
	    if(maj_temp > 0.5) {
	    h_TmajBadpT->Fill(pt[naxis]);
	    h_TmajBad->Fill(maj_temp);
	    } 
	    if(min_temp > 0.5) {
	    h_TminBadpT->Fill(pt[naxis]);
	    h_TminBad->Fill(maj_temp);
	    } 
	  */
	}   
      }//end of major/minor axis loop
      timer.Stop();
      
      //fill all the maximum values before finishing
      // if(jetCount > 1){
	
      h_thrust[cBin]->Fill(thrust_max);
      h_eta[cBin]->Fill(eta_v[max_nref]);
      h_phi[cBin]->Fill(phi_v[max_nref]);
      h_min[cBin]->Fill(thrust_min_max);
      h_maj[cBin]->Fill(thrust_maj_max);
      h_nref[cBin]->Fill(nref);
      h_jetCount[cBin]->Fill(NJets_Sel);
	
      if(debug) {
	if (thrust_max < 0.5)     {  cout << "FLAG_thrust1: " << thrust_max <<  " , " << jetCount << endl; }
	if (thrust_maj_max > 0.5) {  cout << "FLAG_maj: " << thrust_maj_max <<  " , " << jetCount << endl; }
	if (thrust_min_max > 0.5) {  cout << "FLAG_min: " << thrust_min_max <<  " , " << jetCount << endl; }
      }	
      //if(jt80)    h_80->Fill(thrust_max,jt80_pre * pThat_weight);
      //if(jt60)    h_60->Fill(thrust_max,jt60_pre * pThat_weight);
      //if(jt40)    h_40->Fill(thrust_max,jt40_pre * pThat_weight);
      //}

      pt_v.clear();
      eta_v.clear();
      phi_v.clear();

      px.clear();
      py.clear();
      pz.clear();
      
    }//end of event loop


    
    gROOT->GetListOfFiles()->Remove(file);
    //gROOT->GetListOfFiles()->Remove(weight);
    
    cout << "Events Selected: " << eventCount << endl;
    cout << "File Finished" << endl; 
    
  }//end file loop

  //scale the histograms
  Double_t integral;
  
  // integral = h_thrust->Integral();
  // h_thrust->Scale(1/integral);
  //h_thrust->Scale(1./h_thrust->Integral());
  //h_maj->Scale(1./h_maj->Integral());
  //h_min->Scale(1./h_min->Integral());

  // integral = h_maj->Integral(); 
  // h_maj->Scale(1/integral);

  // integral = h_min->Integral();
  // h_min->Scale(1/integral);

  //integral = h_80->Integral();
  //h_80->Scale(integral);

  //integral = h_60->Integral();
  //h_60->Scale(integral);

  // integral = h_40->Integral();
  //h_40->Scale(integral); 
 
  //Create the plot for Thrust vs. dN/dT
  //define histograms
  // TH1F * h_T = DivideByBinWidth(h_thrust[], "thrust_scaled");
  // TH1F * h_Tmaj = DivideByBinWidth(h_maj, "thrust_maj_scaled");
  // TH1F * h_Tmin = DivideByBinWidth(h_min, "thrust_min_scaled");
  
  //Float_t divEntries = 1./(h_thrust->GetBinWidth(1));
  
  //h_T->Scale(divEntries);
  //h_Tmaj->Scale(divEntries);
  //h_Tmin->Scale(divEntries);
  
  //h_40 = DivideByBinWidth(h_40, "thrust_40_new");   h_40->Scale(divEntries);
  //h_60 = DivideByBinWidth(h_60, "thrust_60_new");   h_60->Scale(divEntries);
  //h_80 = DivideByBinWidth(h_80, "thrust_80_new");   h_80->Scale(divEntries);

  // h_T->Print("base");
  // h_Tmaj->Print("base");
  // h_Tmin->Print("base");
  // h_pT->Print("base");
  // h_pTcut->Print("base");
  // //h_40->Print("base");
  // //h_60->Print("base");
  // //h_80->Print("base");
  // h_nref->Print("base");
  // h_jetCount->Print("base");
  // h_eta->Print("base");
  // h_phi->Print("base");
  // h_weight->Print("base"); 
  
  // h_T->Write();
  // h_Tmaj->Write();
  // h_Tmin->Write();
  // h_pT->Write();
  // h_pTcut->Write();
  // //h_40->Write();
  // //h_60->Write();
  // //h_80->Write();
  // h_nref->Write();
  // h_jetCount->Write();
  // h_eta->Write();
  // h_phi->Write();
  // h_weight->Write(); 
  
  save_File->Write();
  save_File->Close();

  cout<<endl<<endl<<endl<<endl<<"GOING TO WRITE BAD OUTPUT FILE"<<endl<<endl<<endl<<endl;
  
  //if(debug) {
    
  // TFile * bad_File = new TFile(kFoname2.c_str(),"RECREATE");  
  // bad_File->cd();
  
  // h_TBad->Print("base");
  // h_TmajBad->Print("base");
  // h_TminBad->Print("base");
  // h_TBadpT->Print("base");
  // h_TmajBadpT->Print("base");
  // h_TminBadpT->Print("base");
  // h_etaBad->Print("base");
  // h_phiBad->Print("base");
  // h_nrefBad->Print("base");
  // h_jetCountBad->Print("base");
  // h_pthatBad->Print("base");
  // h_weightBad->Print("base");
  // h_fileNum->Print("base"); 
    
  // h_TBad->Write();
  // h_TmajBad->Write();
  // h_TminBad->Write();
  // h_TBadpT->Write();
  // h_TmajBadpT->Write();
  // h_TminBadpT->Write();
  // h_etaBad->Write();
  // h_phiBad->Write();
  // h_nrefBad->Write();
  // h_jetCountBad->Write();
  // h_pthatBad->Write();
  // h_weightBad->Write();
  // h_fileNum->Write();
    
  // bad_File->Write();
  // bad_File->Close();
  // // }
  
  timer.Stop();
  cout<<"Macro finished: "<<endl;
  
  cout<<"CPU time (min)  = "<<(Float_t)timer.CpuTime()/60<<endl;
  cout<<"Real time (min) = "<<(Float_t)timer.RealTime()/60<<endl;
  
}//end of plot thrust
예제 #13
0
void GameManager::Collision(FlyObject* objectA, FlyObject* objectB)
{
	int type_ = 0;
	if (objectA->Name() == "Player" || objectB->Name() == "Player")
	{
		if (objectB->Name() == "Player"){
			std::swap(objectA, objectB);
		}
		Player* play = static_cast<Player*>(objectA);

		if (objectB->Name() == "EnemyBomb")
		{
			Weapon *bomb = static_cast<Weapon*>(objectB);
			Produce(_T("Explosion"), Point(objectB->X() + objectB->Width() / 2, objectB->Y() + objectB->Height() / 2));
			if (!God()){ play->SubHP(bomb->Power());}
			if (play->HP() <= 0){
				//play->Killed();
				OverGame();}
			bomb->Killed();
		}
		if (objectB->Name() == "Enemy")
		{
			Plane *enemy = static_cast<Plane *>(objectB);
			if (enemy->DetailedName() == "Box" || enemy->DetailedName() == "BossLeft" || enemy->DetailedName() == "BossMid" || enemy->DetailedName() == "BossRight") return;
			Produce(_T("Explosion"), Point(objectB->X() + objectB->Width() / 2, objectB->Y() + objectB->Height() / 2));

			if (!God()) play->SubHP(1);
			if (play->HP() <= 0) {
				//play->Killed();
				OverGame();
			}

			if (enemy->DetailedName() == "EnemyPrimaryPlane")
			{
				factory_.ProduceTool(5, *(enemy->Position()), enemy->DetailedName());
			}
			else if (enemy->DetailedName() == "PropellerPlane")
			{
				factory_.ProduceTool(6, *(enemy->Position()), enemy->DetailedName());
			}
			else if (enemy->DetailedName() == "Tank")
			{
				factory_.ProduceTool(7, *(enemy->Position()), enemy->DetailedName());
			}
			else if (enemy->DetailedName() == "Box")
			{
				factory_.ProduceTool(Rand(5, 7), *(enemy->Position()), enemy->DetailedName());
			}

			enemy->Killed();

		}
		if (objectB->Name() == "Tool")
		{
			Tool *tool = static_cast<Tool *>(objectB);
			play->AddTool(tool->DetailedName(),tool->EnemyName(),tool->AddMark());
			tool->DestroyTool();
		}
	}
	else if (objectA->Name() == "PlayerBomb" || objectB->Name() == "PlayerBomb")
	{
		if (objectB->Name() == "PlayerBomb")
		{
			std::swap(objectA,objectB);
		}
		Weapon* bomb = static_cast<Weapon*>(objectA);
		
		if (objectB->Name() == "Enemy")
		{
			Plane* enemy = static_cast<Plane*>(objectB);
			bomb->Killed();
			enemy->SubHP(bomb->Power());
			if (enemy->HP() <= 0)
			{
				Produce(_T("Explosion"),Point(objectB->X() + objectB->Width()/2, objectB->Y() + objectB->Height() / 2));
				if (enemy->DetailedName() == "EnemyPrimaryPlane")
				{
					factory_.ProduceTool(5, *(enemy->Position()),enemy->DetailedName());
				}
				else if (enemy->DetailedName() == "PropellerPlane")				
				{
					factory_.ProduceTool(6, *(enemy->Position()), enemy->DetailedName());
				}
				else if (enemy->DetailedName() == "Tank")
				{
					factory_.ProduceTool(7, *(enemy->Position()), enemy->DetailedName());
				}
				else if (enemy->DetailedName() == "Box")
				{
					factory_.ProduceTool(Rand(5,7), *(enemy->Position()), enemy->DetailedName());
				}
				enemy->Killed();
			}

		}
	}
}
예제 #14
0
void GameWorld::updategame(float dt){
    //CCLOG("update game");
    
    Vector<Plane*> targets2Delete;
    //CCLOG("111, _targets: %zd.", _targets.size());
    Vector<Plane*>::iterator iter;//;
    for (iter = _targets.begin(); iter != _targets.end(); iter++) {
        // target的碰撞体积
        Plane* target = dynamic_cast<Plane*>(*iter);
        Rect targetRect = target->boundingBox();
        // plane的碰撞矩形
        Rect planeRect = _myPlane->boundingBox();
        // plane与target的碰撞检测
        if(targetRect.intersectsRect(planeRect)){
            if(target->getTag() == 4){
                CCLOG("package\n");
                // if package and plane collide
                //doubleBulletFlag = true;
                this->scheduleOnce(schedule_selector(GameWorld::setDoubleBulletFlagF), 5);
                targets2Delete.pushBack(target);
            } else {
                CCLOG("game end.");
                // if enemy and plane collide
                auto gameOverScene = GameOverScene::create();
                gameOverScene->getLayer()->getLabel()->setString(" ");
                gameOverScene->getLayer()->setCurrentScore(score);
                // converts 'int' to 'string'
                std::stringstream ss;
                std::string str;
                ss<<score;
                ss>>str;
                const char *pHighScore = str.c_str();
                // converts 'const char *' to 'int'
                const char *highScore = localStorageGetItem("high_score").c_str();
                if(highScore != NULL ){
                    int highScoreInt = std::atoi(highScore);
                    // If higher than the highest score ,your score will replace it;
                    if(highScoreInt<score)
                        CCLOG("high_score: %s.", pHighScore);
                        localStorageSetItem("high_score", pHighScore);
                }else{
                    localStorageSetItem("high_score", pHighScore);
                    CCLOG("high_score: %s.", pHighScore);
                }
                gameOverScene->getLayer()->getScore()->setString(pHighScore);
                Director::getInstance()->replaceScene(gameOverScene);
            }
        }
        
        //CCLOG("222, bullet: %zd.", _bullets.size());
        Vector<Sprite*> bullets2Delete;
        Vector<Sprite*>::iterator iterB;
        //bullet与target的碰撞
        for (iterB = _bullets.begin(); iterB != _bullets.end(); iterB++) {
        //CCARRAY_FOREACH(_bullets, bulletsIterator){
            auto bullet = dynamic_cast<Sprite*>(*iterB);
            Rect bulletRect = bullet->boundingBox();
            if(targetRect.intersectsRect(bulletRect)){
                target->attacked++;
                //CCLOG("target attacked: %d.", target->attacked);
                bullets2Delete.pushBack(bullet);
            }
        }
        
        /*
         CCLOG("333");
        for (iterB = bullets2Delete.begin(); iterB != bullets2Delete.end(); iter++) {
        //CCARRAY_FOREACH(bullets2Delete, bulletsIterator){
            auto bullet = dynamic_cast<Sprite*>(*iterB);
            _bullets.eraseObject(bullet);
            this->removeChild(bullet);
        }*/
        
        if(target->attacked >= target->attackedCount){
            targets2Delete.pushBack(target);
        }
        bullets2Delete.clear();
    }
    
    //CCLOG("444, targets2Delete: %zd.", targets2Delete.size());
    for (iter = targets2Delete.begin(); iter != targets2Delete.end(); iter++) {
    //CCARRAY_FOREACH(targets2Delete, targetIterator){
        auto target = dynamic_cast<Plane*>(*iter);
        _targets.eraseObject(target);
        if(target->getTag() == 1){
            score+=10;
        }else if(target->getTag() == 2){
            score+=20;
        }else if(target->getTag() == 3){
            score+=50;
            //CocosDenshion::SimpleAudioEngine::sharedEngine()->playEffect("explosion.mp3");
        }else if(target->getTag() == 4){
            CCLOG("target is the package");
            this->scheduleOnce(schedule_selector(GameWorld::setDoubleBulletFlagF), 5);
            doubleBulletFlag = true;
        }
        this->removeChild(target);
        std::stringstream ss;
        std::string str;
        ss<<score;
        ss>>str;
        const char *p = str.c_str();
        scoreLabel->setString(p);
        //CCLOG("888");
    }
    targets2Delete.clear();
    //CCLOG("555");
}
/*!
 * \brief BestFitPlane::setUpResult
 * \param plane
 * \return
 */
bool BestFitPlane::setUpResult(Plane &plane){

    //get and check input observations
    if(!this->inputElements.contains(0) || this->inputElements[0].size() < 3){
        emit this->sendMessage(QString("Not enough valid observations to fit the plane %1").arg(plane.getFeatureName()), eWarningMessage);
        return false;
    }
    QList<QPointer<Observation> > inputObservations;
    foreach(const InputElement &element, this->inputElements[0]){
        if(!element.observation.isNull() && element.observation->getIsSolved() && element.observation->getIsValid()
                && element.shouldBeUsed){
            inputObservations.append(element.observation);
            this->setIsUsed(0, element.id, true);
            continue;
        }
        this->setIsUsed(0, element.id, false);
    }
    if(inputObservations.size() < 3){
        emit this->sendMessage(QString("Not enough valid observations to fit the plane %1").arg(plane.getFeatureName()), eWarningMessage);
        return false;
    }

    //centroid
    OiVec centroid(4);
    foreach(const QPointer<Observation> &obs, inputObservations){
        centroid = centroid + obs->getXYZ();
    }
예제 #16
0
void Frustum::CalculateFrustum(float angle, float ratio, float near, float far,
                               Vector3D &camPos, Vector3D &lookAt, Vector3D &up)
{
   Vector3D xVec, yVec, zVec;
	Vector3D vecN, vecF;
	Vector3D nearTopLeft, nearTopRight,
	         nearBottomLeft, nearBottomRight;
   Vector3D farTopLeft, farTopRight,
            farBottomLeft, farBottomRight;

	float radians = (float)tan((DEG_TO_RAD(angle)) * 0.5);
	float nearH = near  * radians;
	float nearW = nearH * ratio;
	float farH = far    * radians;
	float farW = farH   * ratio;

	zVec = camPos - lookAt;
	zVec.Normalize();

	xVec = up.CrossProduct(zVec);
	xVec.Normalize();

	yVec = zVec.CrossProduct(xVec);

	vecN = camPos - zVec * near;
	vecF = camPos - zVec * far;

	nearTopLeft     = vecN + yVec * nearH - xVec * nearW;
	nearTopRight    = vecN + yVec * nearH + xVec * nearW;
	nearBottomLeft  = vecN - yVec * nearH - xVec * nearW;
	nearBottomRight = vecN - yVec * nearH + xVec * nearW;

	farTopLeft      = vecF + yVec * farH - xVec * farW;
	farTopRight     = vecF + yVec * farH + xVec * farW;
	farBottomLeft   = vecF - yVec * farH - xVec * farW;
	farBottomRight  = vecF - yVec * farH + xVec * farW;

   m_frustum.clear();

   Plane plane;

   plane.CreatePlaneFromTri(nearTopRight, nearTopLeft,
                            farTopLeft);
   AddPlane(plane);

   plane.CreatePlaneFromTri(nearBottomLeft, nearBottomRight,
                            farBottomRight);
   AddPlane(plane);

   plane.CreatePlaneFromTri(nearTopLeft, nearBottomLeft,
                            farBottomLeft);
   AddPlane(plane);

   plane.CreatePlaneFromTri(nearBottomRight, nearTopRight,
                            farBottomRight);
   AddPlane(plane);

   plane.CreatePlaneFromTri(nearTopLeft, nearTopRight,
                            nearBottomRight);
   AddPlane(plane);

   plane.CreatePlaneFromTri(farTopRight, farTopLeft,
                            farBottomLeft);
   AddPlane(plane);
}
예제 #17
0
파일: CelShadeApp.cpp 프로젝트: endy/Ivy
///////////////////////////////////////////////////////////////////////////////////////////////////
/// CelShadeApp::CelShadeD3D
///
/// @brief
///     Render a cel-shading demo using Direct3D
/// @return
///     N/A
///////////////////////////////////////////////////////////////////////////////////////////////////
void CelShadeApp::CelShadeD3D()
{
    ID3D11DeviceContext* pContext = m_pDxData->pD3D11Context;
    ID3D11Device* pDevice = m_pDxData->pD3D11Device;

    D3DX11_IMAGE_LOAD_INFO imageLoadInfo;
    memset( &imageLoadInfo, 0, sizeof(D3DX11_IMAGE_LOAD_INFO) );
    imageLoadInfo.BindFlags = D3D11_BIND_SHADER_RESOURCE;
    imageLoadInfo.Format = DXGI_FORMAT_R8G8B8A8_UNORM;

    DxTextureCreateInfo shadeTexInfo;
    memset(&shadeTexInfo, 0, sizeof(DxTextureCreateInfo));
    shadeTexInfo.flags.RenderTarget = TRUE;
    shadeTexInfo.flags.ShaderInput = TRUE;
    shadeTexInfo.format = DXGI_FORMAT_R8G8B8A8_UNORM;
    shadeTexInfo.width = m_screenWidth;
    shadeTexInfo.height = m_screenHeight;
    DxTexture* pShadeTex = DxTexture::Create(pDevice, &shadeTexInfo);

    DxTextureCreateInfo edgeTexInfo;
    memset(&edgeTexInfo, 0, sizeof(DxTextureCreateInfo));
    edgeTexInfo.flags.RenderTarget = TRUE;
    edgeTexInfo.flags.ShaderInput = TRUE;
    edgeTexInfo.format = DXGI_FORMAT_R8G8B8A8_UNORM;
    edgeTexInfo.width = m_screenWidth;
    edgeTexInfo.height = m_screenHeight;
    DxTexture* pEdgeTex = DxTexture::Create(pDevice, &edgeTexInfo);

    // Samplers  /////////////////////////////////////////////////////////////////////////////

    // SamplerState PointSampler : register(s0);

    D3D11_SAMPLER_DESC pointSamplerDesc;
    memset(&pointSamplerDesc, 0, sizeof(D3D11_SAMPLER_DESC));
    pointSamplerDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_POINT;
    pointSamplerDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
    pointSamplerDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
    pointSamplerDesc.AddressW = D3D11_TEXTURE_ADDRESS_CLAMP;
    pointSamplerDesc.MinLOD = -FLT_MAX;
    pointSamplerDesc.MaxLOD = FLT_MAX;
    pointSamplerDesc.MipLODBias = 0.0f;
    pointSamplerDesc.MaxAnisotropy = 16;

    ID3D11SamplerState* pPointSampler = NULL;
    pDevice->CreateSamplerState(&pointSamplerDesc, &pPointSampler);

    //
    UINT numVertices = 0, numIndices = 0;
    VertexPTN* pVB = NULL;
    UINT* pIB = NULL;
    ImportPly("Content/dragon_vrip_res3.ply", numVertices, &pVB, numIndices, &pIB);
    //ImportPly("Content/bun_zipper_res4.ply", numVertices, &pVB, numIndices, &pIB);
    DxMeshCreateInfo meshCreateInfo = {0};
    meshCreateInfo.indexCount = numIndices;
    meshCreateInfo.pIndexArray = pIB;
    meshCreateInfo.indexFormat = DXGI_FORMAT_R32_UINT;
    meshCreateInfo.pVertexArray = pVB;
    meshCreateInfo.vertexCount = numVertices;
    meshCreateInfo.vertexElementSize = sizeof(VertexPTN);
    DxMesh* pMesh = DxMesh::Create(pDevice, &meshCreateInfo);

    Plane p;
    DxMeshCreateInfo planeMeshInfo;
    memset(&planeMeshInfo, 0, sizeof(planeMeshInfo));
    planeMeshInfo.pVertexArray = p.GetVB();
    planeMeshInfo.vertexCount = p.NumVertices();
    planeMeshInfo.vertexElementSize = sizeof(VertexPTN);

    DxMesh* pPlaneMesh = DxMesh::Create(pDevice, &planeMeshInfo);

    Cube c;
    DxMeshCreateInfo cubeMeshInfo;
    memset(&cubeMeshInfo, 0, sizeof(cubeMeshInfo));
    cubeMeshInfo.pVertexArray = c.GetVB();
    cubeMeshInfo.vertexCount = c.NumVertices();
    cubeMeshInfo.vertexElementSize = sizeof(VertexPT);

    DxMesh* pCubeMesh = DxMesh::Create(pDevice, &cubeMeshInfo);

    D3D11_SUBRESOURCE_DATA cbInitData;
    memset(&cbInitData, 0, sizeof(D3D11_SUBRESOURCE_DATA));	

    // Camera Buffer
    CameraBufferData cameraData;
    memset(&cameraData, 0, sizeof(CameraBufferData));

    DxBufferCreateInfo cameraBufferCreateInfo = {0};
    cameraBufferCreateInfo.flags.cpuWriteable = TRUE;
    cameraBufferCreateInfo.elemSizeBytes = sizeof(CameraBufferData);
    cameraBufferCreateInfo.pInitialData = &cameraData;
    DxBuffer* pCameraBuffer = DxBuffer::Create(pDevice, &cameraBufferCreateInfo);

    // Shaders ////////////////////////////////////////////////////////////////////////////////////

    m_pPosTexTriVS = DxShader::CreateFromFile(pDevice, "PosTexTri", "Content/shaders/CelShade.hlsl", PosTexVertexDesc, PosTexElements);
    m_pPosTexNormVS = DxShader::CreateFromFile(pDevice, "PosTexNorm", "Content/shaders/CelShade.hlsl", PosTexNormVertexDesc, PosTexNormElements);

    m_pCelShadePS = DxShader::CreateFromFile(pDevice, "CelShade", "Content/shaders/CelShade.hlsl");
    DxShader* pDetectEdges = DxShader::CreateFromFile(pDevice, "DetectEdges", "Content/shaders/CelShade.hlsl");
    DxShader* pApplyTexPS = DxShader::CreateFromFile(pDevice, "ApplyTex", "Content/shaders/CelShade.hlsl");

    DxShader* pCubeVS = DxShader::CreateFromFile(pDevice, "PosTex", "Content/shaders/CelShade.hlsl", PosTexVertexDesc, PosTexElements);
    DxShader* pCubePS = DxShader::CreateFromFile(pDevice, "CubePS", "Content/shaders/CelShade.hlsl");


    ////////////////////////////////////////////////////////////////////////////////////////

    pContext->ClearState();

    // SET RENDER STATE

    FLOAT clearColor[4];
    clearColor[0] = 0.2f;
    clearColor[1] = 0.2f;
    clearColor[2] = 0.2f; 
    clearColor[3] = 1.0f;

    D3D11_RASTERIZER_DESC shadeDesc;
    shadeDesc.FillMode = D3D11_FILL_SOLID;
    shadeDesc.CullMode = D3D11_CULL_BACK;
    shadeDesc.FrontCounterClockwise = FALSE;
    shadeDesc.DepthBias = 0;
    shadeDesc.DepthBiasClamp = 0.0f;
    shadeDesc.SlopeScaledDepthBias = 0;
    shadeDesc.DepthClipEnable = false;
    shadeDesc.ScissorEnable = false;
    shadeDesc.MultisampleEnable = false;
    shadeDesc.AntialiasedLineEnable = false;

    ID3D11RasterizerState* pShadeRS = NULL;
    pDevice->CreateRasterizerState(&shadeDesc, &pShadeRS);

    pContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);

    m_pWindow->Show();

    BOOL quit = false;
    FLOAT yRotationAngle = 0.0f;
    while (!quit)
    {
        ProcessUpdates();

        BeginFrame();

        CameraBufferData* pCameraData = NULL;

        // new frame, clear state
        pContext->ClearState();

        pContext->RSSetViewports(1, &m_pDxData->viewport);
        pContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);

        pContext->RSSetState(pShadeRS);
        pContext->PSSetSamplers(0, 1, &pPointSampler);

        pContext->OMSetRenderTargets(1,
                                       &m_pDxData->pAppRenderTargetView,
                                       m_pDxData->pAppDepthStencilTex->GetDepthStencilView());
        pContext->ClearRenderTargetView(m_pDxData->pAppRenderTargetView, clearColor);
        pContext->ClearDepthStencilView(m_pDxData->pAppDepthStencilTex->GetDepthStencilView(),
                                          D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL,
                                          1.0,
                                          0);

        ///// Draw Mesh ///////////////////////////////////////////////////////////////////////////

        FLOAT viewRotationY = (GetMousePos().x - (m_screenWidth / 2.0f)) /(m_screenWidth / 2.0f);
        viewRotationY *= (3.14159f / 4.0f);

        FLOAT viewRotationZ = (GetMousePos().y - (m_screenHeight / 2.0f)) /(m_screenHeight / 2.0f);
        viewRotationZ *= (3.14159f / 4.0f);

        pCameraData = reinterpret_cast<CameraBufferData*>(pCameraBuffer->Map(pContext));
        pCameraData->worldMatrix = XMMatrixScaling(25, 25, 25) * XMMatrixRotationY(yRotationAngle) *
                                   XMMatrixTranslation(m_pCamera->Position().x,
                                                       m_pCamera->Position().y,
                                                       m_pCamera->Position().z) ;
        // translate world +6 in Z to position camera -9 from world origin
        pCameraData->viewMatrix = m_pCamera->W2C();
        pCameraData->projectionMatrix = m_pCamera->C2S();

        pCameraBuffer->Unmap(pContext);

        pCameraBuffer->BindVS(pContext, 0);

        pMesh->Bind(pContext);

        m_pPosTexNormVS->Bind(pContext);
        m_pCelShadePS->Bind(pContext);
        pMesh->Draw(pContext);

        ///// Detect Edges ///////////////////////////////////////////////////////////////////////////


        ///// Draw Light Position ////////////////////////////////////////////////////////////////////

        //yRotationAngle = 0;
        pCameraData = reinterpret_cast<CameraBufferData*>(pCameraBuffer->Map(pContext));
        pCameraData->worldMatrix = XMMatrixScaling(1, 1, 1);
                                 //  XMMatrixRotationY(yRotationAngle);
                                  // XMMatrixTranslation(-10, 10, 10);
        // translate world +6 in Z to position camera -9 from world origin
        pCameraData->viewMatrix = XMMatrixTranslation(0, 0, 10) * m_pCamera->W2C();
        pCameraData->projectionMatrix = m_pCamera->C2S();

        pCameraBuffer->Unmap(pContext);
        pCameraBuffer->BindVS(pContext, 0);

        pCubeVS->Bind(pContext);

        pCubePS->Bind(pContext);

        pCubeMesh->Bind(pContext);
        pCubeMesh->Draw(pContext);

        ///// Draw UI ////////////////////////////////////////////////////////////////////////////////

        ///@todo Consider moving the following UI drawing to Draw2D()
        m_pUI->Begin();
        // Draw UI stuff
        m_pUI->RenderRect();
        m_pUI->RenderText();
        m_pUI->End();

        /// Blend UI onto final image
        DrawUI();

        m_pDxData->pDXGISwapChain->Present(0,0);

        EndFrame();

        Sleep(50);
        yRotationAngle += 3.14159f / 60.0f;
    }

    // Shader Resource Views

    pCameraBuffer->Destroy();

    // Shaders
    m_pCelShadePS->Destroy();
    m_pCelShadePS = NULL;

    m_pPosTexTriVS->Destroy();
    m_pPosTexTriVS = NULL;

    m_pPosTexNormVS->Destroy();
    m_pPosTexNormVS = NULL;

    pApplyTexPS->Destroy();
    pApplyTexPS = NULL;

    pPlaneMesh->Destroy();
    pPlaneMesh = NULL;

    // Samplers
    pPointSampler->Release();

    // Rasterizer State
    pShadeRS->Release();

    m_pDxData->pD3D11Context->ClearState();
    m_pDxData->pD3D11Context->Flush(); 
}
예제 #18
0
bool AABB::Intersects(const Plane &plane) const
{
	return plane.Intersects(*this);
}
예제 #19
0
bool
Plane::operator==(const Plane &plane) const
{
    return (plane.direction()==_direction && plane.d()==_d );
}
예제 #20
0
bool Ray::Intersects(const Plane &plane, float *d) const
{
	return plane.Intersects(*this, d);
}
예제 #21
0
	//-----------------------------------------------------------------------
	void ConvexBody::clip( const Plane& pl, bool keepNegative )
	{
		if ( getPolygonCount() == 0 )
			return;

		// current will be used as the reference body
		ConvexBody current;
		current.moveDataFromBody(*this);
		
		OgreAssert( this->getPolygonCount() == 0, "Body not empty!" );
		OgreAssert( current.getPolygonCount() != 0, "Body empty!" );

		// holds all intersection edges for the different polygons
		Polygon::EdgeMap intersectionEdges;

		// clip all polygons by the intersection plane
		// add only valid or intersected polygons to *this
		for ( size_t iPoly = 0; iPoly < current.getPolygonCount(); ++iPoly )
		{

			// fetch vertex count and ignore polygons with less than three vertices
			// the polygon is not valid and won't be added
			const size_t vertexCount = current.getVertexCount( iPoly );
			if ( vertexCount < 3 )
				continue;

			// current polygon
			const Polygon& p = current.getPolygon( iPoly );

			// the polygon to assemble
			Polygon *pNew = allocatePolygon();

			// the intersection polygon (indeed it's an edge or it's empty)
			Polygon *pIntersect = allocatePolygon();
			
			// check if polygons lie inside or outside (or on the plane)
			// for each vertex check where it is situated in regard to the plane
			// three possibilities appear:
			Plane::Side clipSide = keepNegative ? Plane::POSITIVE_SIDE : Plane::NEGATIVE_SIDE;
			// - side is clipSide: vertex will be clipped
			// - side is !clipSide: vertex will be untouched
			// - side is NOSIDE:   vertex will be untouched
			Plane::Side *side = OGRE_ALLOC_T(Plane::Side, vertexCount, MEMCATEGORY_SCENE_CONTROL);
			for ( size_t iVertex = 0; iVertex < vertexCount; ++iVertex )
			{
				side[ iVertex ] = pl.getSide( p.getVertex( iVertex ) );
			}

			// now we check the side combinations for the current and the next vertex
			// four different combinations exist:
			// - both points inside (or on the plane): keep the second (add it to the body)
			// - both points outside: discard both (don't add them to the body)
			// - first vertex is inside, second is outside: add the intersection point
			// - first vertex is outside, second is inside: add the intersection point, then the second
			for ( size_t iVertex = 0; iVertex < vertexCount; ++iVertex )
			{
				// determine the next vertex
				size_t iNextVertex = ( iVertex + 1 ) % vertexCount;

				const Vector3& vCurrent = p.getVertex( iVertex );
				const Vector3& vNext    = p.getVertex( iNextVertex );

				// case 1: both points inside (store next)
				if ( side[ iVertex ]     != clipSide &&		// NEGATIVE or NONE
					 side[ iNextVertex ] != clipSide )		// NEGATIVE or NONE
				{
					// keep the second
					pNew->insertVertex( vNext );
				}

				// case 3: inside -> outside (store intersection)
				else if ( side[ iVertex ]		!= clipSide &&
						  side[ iNextVertex ]	== clipSide )
				{
					// Do an intersection with the plane. We use a ray with a start point and a direction.
					// The ray is forced to hit the plane with any option available (eigher current or next
					// is the starting point)

					// intersect from the outside vertex towards the inside one
					Vector3 vDirection = vCurrent - vNext;
					vDirection.normalise();
					Ray ray( vNext, vDirection );
					std::pair< bool, Real > intersect = ray.intersects( pl );

					// store intersection
					if ( intersect.first )
					{
						// convert distance to vector
						Vector3 vIntersect = ray.getPoint( intersect.second );	

						// store intersection
						pNew->insertVertex( vIntersect );
						pIntersect->insertVertex( vIntersect );
					}
				}

				// case 4: outside -> inside (store intersection, store next)
				else if ( side[ iVertex ]		== clipSide &&
					side[ iNextVertex ]			!= clipSide )
				{
					// Do an intersection with the plane. We use a ray with a start point and a direction.
					// The ray is forced to hit the plane with any option available (eigher current or next
					// is the starting point)

					// intersect from the outside vertex towards the inside one
					Vector3 vDirection = vNext - vCurrent;
					vDirection.normalise();
					Ray ray( vCurrent, vDirection );
					std::pair< bool, Real > intersect = ray.intersects( pl );

					// store intersection
					if ( intersect.first )
					{
						// convert distance to vector
						Vector3 vIntersect = ray.getPoint( intersect.second );

						// store intersection
						pNew->insertVertex( vIntersect );
						pIntersect->insertVertex( vIntersect );
					}

					pNew->insertVertex( vNext );

				}
				// else:
				// case 2: both outside (do nothing)
					
			}

			// insert the polygon only, if at least three vertices are present
			if ( pNew->getVertexCount() >= 3 )
			{
				// in case there are double vertices, remove them
				pNew->removeDuplicates();

				// in case there are still at least three vertices, insert the polygon
				if ( pNew->getVertexCount() >= 3 )
				{
					this->insertPolygon( pNew );
				}
				else
				{
					// delete pNew because it's empty or invalid
					freePolygon(pNew);
					pNew = 0;
				}
			}
			else
			{
				// delete pNew because it's empty or invalid
				freePolygon(pNew);
				pNew = 0;
			}

			// insert intersection polygon only, if there are two vertices present
			if ( pIntersect->getVertexCount() == 2 )
			{
				intersectionEdges.insert( Polygon::Edge( pIntersect->getVertex( 0 ),
														  pIntersect->getVertex( 1 ) ) );
			}

			// delete intersection polygon
			// vertices were copied (if there were any)
			freePolygon(pIntersect);
			pIntersect = 0;

			// delete side info
			OGRE_FREE(side, MEMCATEGORY_SCENE_CONTROL);
			side = 0;
		}

		// if the polygon was partially clipped, close it
		// at least three edges are needed for a polygon
		if ( intersectionEdges.size() >= 3 )
		{
			Polygon *pClosing = allocatePolygon();

			// Analyze the intersection list and insert the intersection points in ccw order
			// Each point is twice in the list because of the fact that we have a convex body
			// with convex polygons. All we have to do is order the edges (an even-odd pair)
			// in a ccw order. The plane normal shows us the direction.
			Polygon::EdgeMap::iterator it = intersectionEdges.begin();

			// check the cross product of the first two edges
			Vector3 vFirst  = it->first;
			Vector3 vSecond = it->second;

			// remove inserted edge
			intersectionEdges.erase( it );

			Vector3 vNext;

			// find mating edge
			if (findAndEraseEdgePair(vSecond, intersectionEdges, vNext))
			{
				// detect the orientation
				// the polygon must have the same normal direction as the plane and then n
				Vector3 vCross = ( vFirst - vSecond ).crossProduct( vNext - vSecond );
				bool frontside = ( pl.normal ).directionEquals( vCross, Degree( 1 ) );

				// first inserted vertex
				Vector3 firstVertex;
				// currently inserted vertex
				Vector3 currentVertex;
				// direction equals -> front side (walk ccw)
				if ( frontside )
				{
					// start with next as first vertex, then second, then first and continue with first to walk ccw
					pClosing->insertVertex( vNext );
					pClosing->insertVertex( vSecond );
					pClosing->insertVertex( vFirst );
					firstVertex		= vNext;
					currentVertex	= vFirst;

				#ifdef _DEBUG_INTERSECTION_LIST
					std::cout << "Plane: n=" << pl.normal << ", d=" << pl.d << std::endl;
					std::cout << "First inserted vertex: " << *next << std::endl;
					std::cout << "Second inserted vertex: " << *vSecond << std::endl;
					std::cout << "Third inserted vertex: " << *vFirst << std::endl;
				#endif
				}
				// direction does not equal -> back side (walk cw)
				else
				{
					// start with first as first vertex, then second, then next and continue with next to walk ccw
					pClosing->insertVertex( vFirst );
					pClosing->insertVertex( vSecond );
					pClosing->insertVertex( vNext );
					firstVertex		= vFirst;
					currentVertex	= vNext;

					#ifdef _DEBUG_INTERSECTION_LIST
						std::cout << "Plane: n=" << pl.normal << ", d=" << pl.d << std::endl;
						std::cout << "First inserted vertex: " << *vFirst << std::endl;
						std::cout << "Second inserted vertex: " << *vSecond << std::endl;
						std::cout << "Third inserted vertex: " << *next << std::endl;
					#endif
				}

				// search mating edges that have a point in common
				// continue this operation as long as edges are present
				while ( !intersectionEdges.empty() )
				{

					if (findAndEraseEdgePair(currentVertex, intersectionEdges, vNext))
					{
						// insert only if it's not the last (which equals the first) vertex
						if ( !intersectionEdges.empty() )
						{
							currentVertex = vNext;
							pClosing->insertVertex( vNext );
						}
					}
					else
					{
						// degenerated...
						break;
					}

				} // while intersectionEdges not empty

				// insert polygon (may be degenerated!)
				this->insertPolygon( pClosing );

			}
			// mating intersection edge NOT found!
			else
			{
				freePolygon(pClosing);
			}

		} // if intersectionEdges contains more than three elements
	}
예제 #22
0
Geometry::MeshData Geometry::build_convex_mesh(const DVector<Plane> &p_planes) {

	MeshData mesh;
	
	
#define SUBPLANE_SIZE 1024.0
	
	float subplane_size = 1024.0; // should compute this from the actual plane
	for (int i=0;i<p_planes.size();i++) {
	
		Plane p =p_planes[i];
		
		Vector3 ref=Vector3(0.0,1.0,0.0);
		
		if (ABS(p.normal.dot(ref))>0.95)
			ref=Vector3(0.0,0.0,1.0); // change axis
			
		Vector3 right = p.normal.cross(ref).normalized();
		Vector3 up = p.normal.cross( right ).normalized();
				
		Vector< Vector3 > vertices;
		
		Vector3 center = p.get_any_point();
		// make a quad clockwise
		vertices.push_back( center - up * subplane_size + right * subplane_size );
		vertices.push_back( center - up * subplane_size - right * subplane_size );
		vertices.push_back( center + up * subplane_size - right * subplane_size );
		vertices.push_back( center + up * subplane_size + right * subplane_size );
		
		for (int j=0;j<p_planes.size();j++) {

			if (j==i)
				continue;
			

			Vector< Vector3 > new_vertices;
			Plane clip=p_planes[j];
			
			if (clip.normal.dot(p.normal)>0.95)
				continue;
				
			if (vertices.size()<3)
				break;
				
			for(int k=0;k<vertices.size();k++) {
			
				int k_n=(k+1)%vertices.size();
				
				Vector3 edge0_A=vertices[k];
				Vector3 edge1_A=vertices[k_n];
				
				real_t dist0 = clip.distance_to(edge0_A);
				real_t dist1 = clip.distance_to(edge1_A);
				
							
				if ( dist0 <= 0 ) { // behind plane 
				
					new_vertices.push_back(vertices[k]);					
				}
				
				
				// check for different sides and non coplanar
				if ( (dist0*dist1) < 0) { 
					
					// calculate intersection
					Vector3 rel = edge1_A - edge0_A;

					real_t den=clip.normal.dot( rel );
					if (Math::abs(den)<CMP_EPSILON)
						continue; // point too short

					real_t dist=-(clip.normal.dot( edge0_A )-clip.d)/den;
					Vector3 inters = edge0_A+rel*dist;
					new_vertices.push_back(inters);
				}			
			}
			
			vertices=new_vertices;
		}
		
		if (vertices.size()<3)
			continue;
		
		
		//result is a clockwise face
		
		MeshData::Face face;
				
		// add face indices
		for (int j=0;j<vertices.size();j++) {
		
			
			int idx=-1;
			for (int k=0;k<mesh.vertices.size();k++) {
		
				if (mesh.vertices[k].distance_to(vertices[j])<0.001) {
				
					idx=k;
					break;
				}
			}
			
			if (idx==-1) {
			
				idx=mesh.vertices.size();
				mesh.vertices.push_back(vertices[j]);
			}
			
			face.indices.push_back(idx);
		}
		face.plane=p;
		mesh.faces.push_back(face);
		
		//add edge
		
		for(int j=0;j<face.indices.size();j++) {
		
			int a=face.indices[j];
			int b=face.indices[(j+1)%face.indices.size()];
		
			bool found=false;
			for(int k=0;k<mesh.edges.size();k++) {
		
				if (mesh.edges[k].a==a && mesh.edges[k].b==b) {
					found=true;
					break;
				}
				if (mesh.edges[k].b==a && mesh.edges[k].a==b) {
					found=true;
					break;
				}				
			}
			
			if (found)
				continue;
			MeshData::Edge edge;
			edge.a=a;
			edge.b=b;
			mesh.edges.push_back(edge);
		}
		
		
	}

	return mesh;
}
예제 #23
0
//----------------------------------------------------------------------------
static void SplitAndDecompose (Tetrahedron kTetra, const Plane& rkPlane,
    vector<Tetrahedron>& rkInside)
{
    // determine on which side of the plane the points of the tetrahedron lie
    Real afC[4];
    int i, aiP[4], aiN[4], aiZ[4];
    int iPositive = 0, iNegative = 0, iZero = 0;

    for (i = 0; i < 4; i++)
    {
        afC[i] = rkPlane.DistanceTo(kTetra[i]);
        if ( afC[i] > 0.0f )
            aiP[iPositive++] = i;
        else if ( afC[i] < 0.0f )
            aiN[iNegative++] = i;
        else
            aiZ[iZero++] = i;
    }

    // For a split to occur, one of the c_i must be positive and one must
    // be negative.

    if ( iNegative == 0 )
    {
        // tetrahedron is completely on the positive side of plane, full clip
        return;
    }

    if ( iPositive == 0 )
    {
        // tetrahedron is completely on the negative side of plane
        rkInside.push_back(kTetra);
        return;
    }

    // Tetrahedron is split by plane.  Determine how it is split and how to
    // decompose the negative-side portion into tetrahedra (6 cases).
    Real fW0, fW1, fInvCDiff;
    Vector3 akIntp[4];

    if ( iPositive == 3 )
    {
        // +++-
        for (i = 0; i < iPositive; i++)
        {
            fInvCDiff = 1.0f/(afC[aiP[i]] - afC[aiN[0]]);
            fW0 = -afC[aiN[0]]*fInvCDiff;
            fW1 = +afC[aiP[i]]*fInvCDiff;
            kTetra[aiP[i]] = fW0*kTetra[aiP[i]] + fW1*kTetra[aiN[0]];
        }
        rkInside.push_back(kTetra);
    }
    else if ( iPositive == 2 )
    {
        if ( iNegative == 2 )
        {
            // ++--
            for (i = 0; i < iPositive; i++)
            {
                fInvCDiff = 1.0f/(afC[aiP[i]]-afC[aiN[0]]);
                fW0 = -afC[aiN[0]]*fInvCDiff;
                fW1 = +afC[aiP[i]]*fInvCDiff;
                akIntp[i] = fW0*kTetra[aiP[i]] + fW1*kTetra[aiN[0]];
            }
            for (i = 0; i < iNegative; i++)
            {
                fInvCDiff = 1.0f/(afC[aiP[i]]-afC[aiN[1]]);
                fW0 = -afC[aiN[1]]*fInvCDiff;
                fW1 = +afC[aiP[i]]*fInvCDiff;
                akIntp[i+2] = fW0*kTetra[aiP[i]] + fW1*kTetra[aiN[1]];
            }

            kTetra[aiP[0]] = akIntp[2];
            kTetra[aiP[1]] = akIntp[1];
            rkInside.push_back(kTetra);

            rkInside.push_back(Tetrahedron(kTetra[aiN[1]],akIntp[3],akIntp[2],
                akIntp[1]));

            rkInside.push_back(Tetrahedron(kTetra[aiN[0]],akIntp[0],akIntp[1],
                akIntp[2]));
        }
        else
        {
            // ++-0
            for (i = 0; i < iPositive; i++)
            {
                fInvCDiff = 1.0f/(afC[aiP[i]]-afC[aiN[0]]);
                fW0 = -afC[aiN[0]]*fInvCDiff;
                fW1 = +afC[aiP[i]]*fInvCDiff;
                kTetra[aiP[i]] = fW0*kTetra[aiP[i]] + fW1*kTetra[aiN[0]];
            }
            rkInside.push_back(kTetra);
        }
    }
    else if ( iPositive == 1 )
    {
        if ( iNegative == 3 )
        {
            // +---
            for (i = 0; i < iNegative; i++)
            {
                fInvCDiff = 1.0f/(afC[aiP[0]]-afC[aiN[i]]);
                fW0 = -afC[aiN[i]]*fInvCDiff;
                fW1 = +afC[aiP[0]]*fInvCDiff;
                akIntp[i] = fW0*kTetra[aiP[0]] + fW1*kTetra[aiN[i]];
            }

            kTetra[aiP[0]] = akIntp[0];
            rkInside.push_back(kTetra);

            rkInside.push_back(Tetrahedron(akIntp[0],kTetra[aiN[1]],
                kTetra[aiN[2]],akIntp[1]));

            rkInside.push_back(Tetrahedron(kTetra[aiN[2]],akIntp[1],akIntp[2],
                akIntp[0]));
        }
        else if ( iNegative == 2 )
        {
            // +--0
            for (i = 0; i < iNegative; i++)
            {
                fInvCDiff = 1.0f/(afC[aiP[0]]-afC[aiN[i]]);
                fW0 = -afC[aiN[i]]*fInvCDiff;
                fW1 = +afC[aiP[0]]*fInvCDiff;
                akIntp[i] = fW0*kTetra[aiP[0]] + fW1*kTetra[aiN[i]];
            }

            kTetra[aiP[0]] = akIntp[0];
            rkInside.push_back(kTetra);

            rkInside.push_back(Tetrahedron(akIntp[1],kTetra[aiZ[0]],
                kTetra[aiN[1]],akIntp[0]));
        }
        else
        {
            // +-00
            fInvCDiff = 1.0f/(afC[aiP[0]]-afC[aiN[0]]);
            fW0 = -afC[aiN[0]]*fInvCDiff;
            fW1 = +afC[aiP[0]]*fInvCDiff;
            kTetra[aiP[0]] = fW0*kTetra[aiP[0]] + fW1*kTetra[aiN[0]];
            rkInside.push_back(kTetra);
        }
    }
}
예제 #24
0
파일: main_pk.cpp 프로젝트: Goobae/Shapes
void DisplayGrid()
{
	//cout << "dg\n";

	Window * window = Window::FindCurrentWindow(windows);
	if (window->handle == BAD_GL_VALUE)
		return;

	glViewport(0 , 0 , window->size.x , window->size.y);
	vec4 crimson(0.6f , 0.0f , 0.0f , 1.0f);
	vec3 ambient = vec3(0.0f , 0.0f , 0.0f);
	vec3 specular = vec3(1.0f , 1.0f , 1.0f);
	vec3 diffuse = vec3(0.0f , 0.0f , 0.8f);

	glClearColor(crimson.r , crimson.g , crimson.b , crimson.a);
	glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);
	glEnable(GL_DEPTH_TEST);

	vector<Constellation::PositionData> & pd = gc.GetPositionData();

	mat4 s = scale(mat4() , vec3(50.0f , 50.0f , 1.0f));
	mat4 view_matrix = lookAt(vec3(0.0f , 0.0f , 150.0f) , vec3(0.0f , 0.0f , 0.0f) , vec3(0.0f , 1.0f , 0.0f));
	mat4 projection_matrix = perspective(radians(window->fovy) , window->aspect , window->near_distance , window->far_distance);

	mat4 r = rotate(mat4() , radians(window->LocalTime() * 0.0f) , vec3(0.0f , 1.0f , 0.0f));

	for (vector<Constellation::PositionData>::iterator iter = pd.begin(); iter < pd.end(); iter++)
	{
		mat4 model_matrix = rotate(mat4() , radians(window->LocalTime() * 20.0f) , vec3(0.0f , 1.0f , 0.0f));
		model_matrix = translate(model_matrix , vec3(s * vec4((*iter).location , 1.0f)));

		// Beginning of orientation code.
		//
		// There is an assumption here (we are aligning z axes) that the shape you're building have
		// a natural facing down the z axis.
		//
		// The following orients the object's z axis along the axis held in outward_direction_vector.
		// target_dir gets that value. The difference in direction from the z axis to the desired direction
		// is captured by the dot product. The angle is retrieved with the acos. Then, if there's anything 
		// to do (I suspect the if statement is NOT needed), a rotation axis is made by the cross product
		// (rotating about it will swing the z axes around). Finally, the rotation is done.
		vec3 target_dir = normalize((*iter).outward_direction_vector);
		float rot_angle = acos(dot(target_dir , vec3(0.0f, 0.0f, 1.0f)));
		if (fabs(rot_angle) > glm::epsilon<float>())
		{
			vec3 rot_axis = normalize(cross(target_dir , vec3(0.0f, 0.0f, 1.0f)));
			model_matrix = rotate(model_matrix, rot_angle , rot_axis);
		}
		// End of orientation code.

		model_matrix = scale(model_matrix , vec3(2.0f, 2.0f, 1.0f));
		phong_shader.Use(model_matrix , view_matrix , projection_matrix);
		phong_shader.SetMaterial(diffuse , specular , 64.0f , ambient);
		phong_shader.SetLightPosition(vec3(0.0f , 0.0f , 1000.0f));
		phong_shader.SelectSubroutine(PhongShader::PHONG_WITH_TEXTURE);
		phong_shader.EnableTexture(textures[1] , 0);
		plane2.Draw(false);
		phong_shader.UnUse();
		if (window->draw_normals)
		{
			constant_shader.Use(model_matrix , view_matrix , projection_matrix);
			constant_shader.SetMaterial(diffuse , specular , 64.0f , vec3(1.0f , 1.0f , 1.0f));
			plane2.Draw(true);
			constant_shader.UnUse();
		}
		// Animate the rotation of the objects within the grid.
		(*iter).outward_direction_vector = vec3(r * vec4((*iter).outward_direction_vector, 1.0f));
	}
	glutSwapBuffers();
}
예제 #25
0
파일: Cube.cpp 프로젝트: UIKit0/mowa.cc
void Cube::genCube(float sx, float sy, float sz, int nx, int ny, int nz, bool smoothNormals) {
	int estimatedNumPoints = 2*(nx+1)*(ny+1) + 2*(nx+1)*(nz+1) + 2*(ny+1)*(nz+1);
	
	vertexStream.setNumVertices(estimatedNumPoints);
	vertexStream.setNumIndices((2*nx*ny + 2*nx*nz + 2*ny*nz) * 6);
	
	VertexAttrib* posAttrib = vertexStream.getAttrib("position", TYPE_VEC3);
	vec3* posBuf = (vec3*)posAttrib->getBuffer();
	
	VertexStreamIndex* indexBuf = vertexStream.getIndices();
	//unsigned short* indexBuf2 = vertexStream.getIndices2();
	
	VertexAttrib* normalAttrib = vertexStream.getAttrib("normal", TYPE_VEC3);
	vec3* normalBuf = (vec3*)normalAttrib->getBuffer();
	
	VertexAttrib* texCoord0Attrib = vertexStream.getAttrib("texCoord0", TYPE_VEC2);
	vec2* texCoord0Buf = (vec2*)texCoord0Attrib->getBuffer();
	
	//tabela pomocnicza z iloscia segmentow scianki
	//zrobiona zeby mozna ja bylo uzyac w for(;;){}
	int def[3][2] = {
		{ny, nz},
		{nx, nz},
		{nx, ny}
	};
	
	int axis[] = {
		Plane::X,
		Plane::Y,
		Plane::Z
	};
	
	//rozmiary sicanek
	float size[3][2] = {
		{sy, sz},
		{sx, sz},
		{sx, sy}
	};
	
	//o tyle nalezy przesunac kolejne scianki z pkt (0,0)
	vec3 shift[] = {
		vec3(-sx/2,  0,  0),
		vec3(  0,-sy/2,  0),
		vec3(  0,  0,-sz/2)
	};
	
	//o te wartosci przemnazamy scianke orginalna zeby otrzymac jej odbicie po drugiej stronie
	vec3 mirror[] = {
		vec3( 1, 1, 1),
		vec3(-1, 1,-1),
		vec3( 1, 1,-1),
		vec3( 1,-1, 1),
		vec3( 1, 1, 1),
		vec3( 1,-1,-1)
	};
	
	//		o te wartosci przemnazamy scianke orginalna zeby otrzymac jej odbicie po drugiej stronie
	vec3 normals[] = {
		vec3(-1, 0, 0),
		vec3( 1, 0, 0),
		vec3( 0,-1, 0),
		vec3( 0, 1, 0),
		vec3( 0, 0,-1),
		vec3( 0, 0, 1)
	};
	
	int allIndices = 0;
	int allVertices = 0;
	for(int axisNum=0; axisNum<3; axisNum++) {
		//FloatVertexAttrib planePosAttrib = (FloatVertexAttrib)planeVS.getAttribByName("pos");
		//float[] planePosBuf = planePosAttrib.getBuffer();
		//FloatVertexAttrib planeNormalAttrib = (FloatVertexAttrib)planeVS.getAttribByName("normal");
		//planeNormalAttrib.getBuffer();
		//FloatVertexAttrib planeTexCoord0Attrib = (FloatVertexAttrib)planeVS.getAttribByName("texCoord0");
		//float[] planeTexCoor0Buf = planeTexCoord0Attrib.getBuffer();
		//int[] planeIndexBuf = planeVS.getIndexBuffer().getBuffer();
		
		Plane* plane = new Plane(size[axisNum][0], size[axisNum][1], axis[axisNum], def[axisNum][0], def[axisNum][1]);
		VertexStream planeVS = plane->getVertexStream();
		
		VertexAttrib* planePosAttrib = planeVS.getAttrib("position", TYPE_VEC3);
		vec3* planePosBuf = (vec3*)planePosAttrib->getBuffer();
		
		VertexAttrib* planeTexCoord0Attrib = planeVS.getAttrib("texCoord0", TYPE_VEC2);
		vec2* planeTexCoord0Buf = (vec2*)planeTexCoord0Attrib->getBuffer();
		
		VertexStreamIndex* planeIndexBuf = planeVS.getIndices();		
		
		int numPlaneVertices = planeVS.getNumVertices();//sizeof(planePosBuf)/sizeof(vec3);
		int numPlaneIndices = planeVS.getNumIndices();//sizeof(planeIndexBuf)/sizeof(unsigned short);
		//Log::msg("npv:%d npi:%d", numPlaneVertices, numPlaneIndices);
		
		for(int mirrorSide=0; mirrorSide<2; mirrorSide++) {
			for(int i=0; i<numPlaneVertices; i++) {
				//posBuf[(allVertices+i)*3+0] = ((planePosBuf[i*3  ]) + shift[axisNum].getX()) * mirror[axisNum*2 + mirrorSide].getX();
				//posBuf[(allVertices+i)*3+1] = ((planePosBuf[i*3+1]) + shift[axisNum].getY()) * mirror[axisNum*2 + mirrorSide].getY();
				//posBuf[(allVertices+i)*3+2] = ((planePosBuf[i*3+2]) + shift[axisNum].getZ()) * mirror[axisNum*2 + mirrorSide].getZ();
				posBuf[allVertices+i] = planePosBuf[i] + shift[axisNum];
				posBuf[allVertices+i].x *= mirror[axisNum*2 + mirrorSide].x;
				posBuf[allVertices+i].y *= mirror[axisNum*2 + mirrorSide].y;
				posBuf[allVertices+i].z *= mirror[axisNum*2 + mirrorSide].z;
				if (smoothNormals) {
					//normalBuf[(allVertices+i)*3  ] = posBuf[(allVertices+i)*3  ];
					//normalBuf[(allVertices+i)*3+1] = posBuf[(allVertices+i)*3+1];
					//normalBuf[(allVertices+i)*3+2] = posBuf[(allVertices+i)*3+2];
					normalBuf[allVertices+i] = vec3(posBuf[allVertices+i]);
				}
				else {
					//normalBuf[(allVertices+i)*3  ] = normals[axisNum*2 + mirrorSide].getX();
					//normalBuf[(allVertices+i)*3+1] = normals[axisNum*2 + mirrorSide].getY();
					//normalBuf[(allVertices+i)*3+2] = normals[axisNum*2 + mirrorSide].getZ();
					normalBuf[allVertices+i] = normals[axisNum*2 + mirrorSide];
				}
				//texCoord0Buf[(allVertices+i)*2  ] = planeTexCoor0Buf[i*2  ];
				//texCoord0Buf[(allVertices+i)*2+1] = planeTexCoor0Buf[i*2+1];
				texCoord0Buf[allVertices+i] = planeTexCoord0Buf[i];
			}
			for(int i=0; i<numPlaneIndices; i++) {
				indexBuf[allIndices + i] = allVertices + planeIndexBuf[i];
			}
			
			allVertices += numPlaneVertices;
			allIndices += numPlaneIndices;
		}
		
	}		
}
예제 #26
0
 //circle intersection of direct sphere and direct plane
  Circle meet( const Sphere& s, const Plane& d){
   return (s.dual() ^ d.dual()).dual();
 } 
예제 #27
0
파일: IvyAppDX.cpp 프로젝트: endy/Ivy
///////////////////////////////////////////////////////////////////////////////////////////////////
/// IvyApp::InitDX
///
/// @brief
///     
/// @return
///     N/A
///////////////////////////////////////////////////////////////////////////////////////////////////
bool IvyApp::InitDX()
{
    bool success = true;

    m_pDxData = new IvyAppDxData();
    memset(&m_pDxData->viewport, 0, sizeof(D3D11_VIEWPORT));

    EnumerateAdapters();
    DxEnumDisplayDevices();

    // Create Swap Chain & Device
    DXGI_SWAP_CHAIN_DESC sd;
    ZeroMemory( &sd, sizeof( sd ) );
    sd.BufferCount = BufferCount;
    sd.BufferDesc.Width = m_screenWidth;
    sd.BufferDesc.Height = m_screenHeight;
    sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
    sd.BufferDesc.RefreshRate.Numerator = 60;
    sd.BufferDesc.RefreshRate.Denominator = 1;
    sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
    sd.OutputWindow = m_pWindow->GetHwnd();
    sd.SampleDesc.Count = 1;
    sd.SampleDesc.Quality = 0;
    sd.Windowed = TRUE;

    D3D_FEATURE_LEVEL  FeatureLevelsRequested[2];
    FeatureLevelsRequested[0] = D3D_FEATURE_LEVEL_11_0;
    FeatureLevelsRequested[1] = D3D_FEATURE_LEVEL_10_1;
    UINT               numLevelsRequested = 2;
    D3D_FEATURE_LEVEL  FeatureLevelsSupported;

    if( DxFAIL (D3D11CreateDeviceAndSwapChain( NULL, 
        D3D_DRIVER_TYPE_HARDWARE, 
        NULL, 
        D3D11_CREATE_DEVICE_DEBUG,
        FeatureLevelsRequested, 
        numLevelsRequested, 
        D3D11_SDK_VERSION, 
        &sd, 
        &m_pDxData->pDXGISwapChain, 
        &m_pDxData->pD3D11Device, 
        &FeatureLevelsSupported,
        &m_pDxData->pD3D11Context )))
    {
        success = false;
    }

    if (success)
    {
        ID3D11Texture2D* pBackBuffer = NULL;

        // Get a pointer to the back buffer
        if (DxFAIL(m_pDxData->pDXGISwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&pBackBuffer)))
        {
            success = false;
        }
        else
        {
            // Create a render-target view
            m_pDxData->pD3D11Device->CreateRenderTargetView(pBackBuffer,
                NULL,
                &m_pDxData->pAppRenderTargetView );
            pBackBuffer->Release();
        }
    }


    HRESULT hr = S_OK;

    if (success)
    {
        DxTextureCreateInfo depthStencilCreateInfo;
        memset(&depthStencilCreateInfo, 0, sizeof(DxTextureCreateInfo));
        depthStencilCreateInfo.flags.DepthStencil = TRUE;
        depthStencilCreateInfo.flags.ShaderInput = TRUE;
        depthStencilCreateInfo.format = DXGI_FORMAT_D24_UNORM_S8_UINT; ///@todo texture doesnt read format currently
        depthStencilCreateInfo.width = m_screenWidth;
        depthStencilCreateInfo.height = m_screenHeight;

        m_pDxData->pAppDepthStencilTex = DxTexture::Create(m_pDxData->pD3D11Device, &depthStencilCreateInfo);
    }

    // Setup viewport
    m_pDxData->viewport.Width = static_cast<FLOAT>(m_screenWidth);
    m_pDxData->viewport.Height = static_cast<FLOAT>(m_screenHeight);
    m_pDxData->viewport.MinDepth = 0.0f;
    m_pDxData->viewport.MaxDepth = 1.0f;
    m_pDxData->viewport.TopLeftX = 0;
    m_pDxData->viewport.TopLeftY = 0;

    // Create UI
    ///@todo Move UI creation up into IvyApp once the creation of IvyUI exists
    m_pUI = DxUI::Create();
    m_pUIData = new IvyDxUIData();

    m_pUIData->pUserInterfaceVS = DxShader::CreateFromFile(m_pDxData->pD3D11Device, "PosTexTri", L"Content/shaders/DxUI.hlsl", PosTexVertexDesc, PosTexElements);
    m_pUIData->pUserInterfacePS = DxShader::CreateFromFile(m_pDxData->pD3D11Device, "ApplyTex", L"Content/shaders/DxUI.hlsl");

    CameraBufferData cameraData;
    memset(&cameraData, 0, sizeof(CameraBufferData));

    DxBufferCreateInfo cameraBufferCreateInfo = {0};
    cameraBufferCreateInfo.flags.cpuWriteable = TRUE;
    cameraBufferCreateInfo.elemSizeBytes = sizeof(CameraBufferData);
    cameraBufferCreateInfo.pInitialData = &cameraData;
    m_pUIData->pUserInterfaceCameraBuf = DxBuffer::Create(m_pDxData->pD3D11Device, &cameraBufferCreateInfo);

    Plane p;
    DxMeshCreateInfo planeMeshInfo;
    memset(&planeMeshInfo, 0, sizeof(planeMeshInfo));
    planeMeshInfo.pVertexArray = p.GetVB();
    planeMeshInfo.vertexCount = p.NumVertices();
    planeMeshInfo.vertexElementSize = sizeof(VertexPTN);

    m_pUIData->pUserInterfaceQuad = DxMesh::Create(m_pDxData->pD3D11Device, &planeMeshInfo);

    m_pUIData->pUserInterfaceOverlay = m_pUI->CreateSharedTextureOverlay(m_pDxData->pD3D11Device);

    if (DxFAIL(m_pUIData->pUserInterfaceOverlay->QueryInterface(__uuidof(IDXGIKeyedMutex),
        (LPVOID*) &m_pUIData->pUserInterfaceMutexD3D)))
    {
        success = false;
    }

    D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc;
    srvDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
    srvDesc.Texture2D.MipLevels = 1;
    srvDesc.Texture2D.MostDetailedMip = 0;
    srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;

    m_pDxData->pD3D11Device->CreateShaderResourceView(m_pUIData->pUserInterfaceOverlay, &srvDesc, &m_pUIData->pUserInterfaceSRV);

    D3D11_BLEND_DESC uiBlendDesc;
    memset(&uiBlendDesc, 0, sizeof(D3D11_BLEND_DESC));

    uiBlendDesc.AlphaToCoverageEnable = FALSE;
    uiBlendDesc.IndependentBlendEnable = FALSE;
    uiBlendDesc.RenderTarget[0].BlendEnable = TRUE;

    uiBlendDesc.RenderTarget[0].SrcBlend = D3D11_BLEND_ONE;
    uiBlendDesc.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA;
    uiBlendDesc.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD;
    uiBlendDesc.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ONE;
    uiBlendDesc.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ZERO;
    uiBlendDesc.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD;

    uiBlendDesc.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL;

    ID3D11BlendState* pUIBlendState = NULL;
    m_pDxData->pD3D11Device->CreateBlendState(&uiBlendDesc, &m_pUIData->pUserInterfaceBlendState);

    return success;
}