Beispiel #1
0
const char* FileBrowser::Path(int index) {
    const char* s = StringBrowser::String(index);

    return (s == nil ) ? nil : Normalize(Concat(lastpath, s));
}
Beispiel #2
0
Spectrum InfiniteAreaLight::Le(const RayDifferential &ray) const {
    Vector3f w = Normalize(WorldToLight(ray.d));
    Point2f st(SphericalPhi(w) * Inv2Pi, SphericalTheta(w) * InvPi);
    return Spectrum(Lmap->Lookup(st), SpectrumType::Illuminant);
}
Beispiel #3
0
void NormalizeDisplay()
{
	// kolor tła - zawartość bufora koloru
	glClearColor(1.0, 1.0, 1.0, 1.0);

	// czyszczenie bufora koloru i bufora głębokości
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

	// wybór macierzy modelowania
	glMatrixMode(GL_MODELVIEW);

	// macierz modelowania = macierz jednostkowa
	glLoadIdentity();

	// przesunięcie układu współrzędnych obiektu do środka bryły odcinania
	glTranslatef(0, 0, -(near + far) / 2);

	// obroty obiektu
	glRotatef(rotatex, 1.0, 0, 0);
	glRotatef(rotatey, 0, 1.0, 0);

	// skalowanie obiektu - klawisze "+" i "-"
	glScalef(scale, scale, scale);

	// włączenie testu bufora głębokości
	glEnable(GL_DEPTH_TEST);

	// włączenie oświetlenia
	glEnable(GL_LIGHTING);

	// włączenie światła GL_LIGHT0 z parametrami domyślnymi
	glEnable(GL_LIGHT0);

	// właściwości materiału
	glMaterialfv(GL_FRONT, GL_AMBIENT, ambient);
	glMaterialfv(GL_FRONT, GL_DIFFUSE, diffuse);
	glMaterialfv(GL_FRONT, GL_SPECULAR, specular);
	glMaterialf(GL_FRONT, GL_SHININESS, shininess);

	// włączenie automatycznej normalizacji wektorów normalnych
	// lub automatycznego skalowania jednostkowych wektorów normalnych
	if (rescale_normal == true)
		glEnable(GL_RESCALE_NORMAL);
	else
		glEnable(GL_NORMALIZE);

	// początek definicji obiektu
	glBegin(GL_TRIANGLES);

	// generowanie obiektu gładkiego - jeden uśredniony
	// wektor normalny na wierzchołek
	if (normals == NORMALS_SMOOTH)
		for (int i = 0; i < 4; i++)
		{
			// obliczanie wektora normalnego dla pierwszego wierzchołka
			GLfloat n[3];
			n[0] = n[1] = n[2] = 0.0;

			// wyszukanie wszystkich ścian posiadających bie¿ący wierzchołek
			for (int j = 0; j < 4; j++)
				if (3 * triangles[3 * i + 0] == 3 * triangles[3 * j + 0] ||
					3 * triangles[3 * i + 0] == 3 * triangles[3 * j + 1] ||
					3 * triangles[3 * i + 0] == 3 * triangles[3 * j + 2])
				{
					// dodawanie wektorów normalnych poszczególnych ścian
					GLfloat nv[3];
					Normal(nv, j);
					n[0] += nv[0];
					n[1] += nv[1];
					n[2] += nv[2];
				}

			// uśredniony wektor normalny jest normalizowany tylko, gdy biblioteka
			// obsługuje automatyczne skalowania jednostkowych wektorów normalnych
			if (rescale_normal == true)
				Normalize(n);
			glNormal3fv(n);
			glVertex3fv(&vertex[3 * triangles[3 * i + 0]]);

			// obliczanie wektora normalnego dla drugiego wierzchołka
			n[0] = n[1] = n[2] = 0.0;

			// wyszukanie wszystkich ścian posiadających bie¿ący wierzchołek
			for (int j = 0; j < 4; j++)
				if (3 * triangles[3 * i + 1] == 3 * triangles[3 * j + 0] ||
					3 * triangles[3 * i + 1] == 3 * triangles[3 * j + 1] ||
					3 * triangles[3 * i + 1] == 3 * triangles[3 * j + 2])
				{
					// dodawanie wektorów normalnych poszczególnych ścian
					GLfloat nv[3];
					Normal(nv, j);
					n[0] += nv[0];
					n[1] += nv[1];
					n[2] += nv[2];
				}

			// uśredniony wektor normalny jest normalizowany tylko, gdy biblioteka
			// obsługuje automatyczne skalowania jednostkowych wektorów normalnych
			if (rescale_normal == true)
				Normalize(n);
			glNormal3fv(n);
			glVertex3fv(&vertex[3 * triangles[3 * i + 1]]);

			// obliczanie wektora normalnego dla trzeciego wierzchołka
			n[0] = n[1] = n[2] = 0.0;

			// wyszukanie wszystkich ścian posiadających bie¿ący wierzchołek
			for (int j = 0; j < 4; j++)
				if (3 * triangles[3 * i + 2] == 3 * triangles[3 * j + 0] ||
					3 * triangles[3 * i + 2] == 3 * triangles[3 * j + 1] ||
					3 * triangles[3 * i + 2] == 3 * triangles[3 * j + 2])
				{
					// dodawanie wektorów normalnych poszczególnych ścian
					GLfloat nv[3];
					Normal(nv, j);
					n[0] += nv[0];
					n[1] += nv[1];
					n[2] += nv[2];
				}

			// uśredniony wektor normalny jest normalizowany tylko, gdy biblioteka
			// obsługuje automatyczne skalowania jednostkowych wektorów normalnych
			if (rescale_normal == true)
				Normalize(n);
			glNormal3fv(n);
			glVertex3fv(&vertex[3 * triangles[3 * i + 2]]);
		}
	else

		// generowanie obiektu "płaskiego" - jeden wektor normalny na ścianę
		for (int i = 0; i < 4; i++)
		{
			GLfloat n[3];
			Normal(n, i);

			// uśredniony wektor normalny jest normalizowany tylko, gdy biblioteka
			// obsługuje automatyczne skalowania jednostkowych wektorów normalnych
			if (rescale_normal == true)
				Normalize(n);
			glNormal3fv(n);
			glVertex3fv(&vertex[3 * triangles[3 * i + 0]]);
			glVertex3fv(&vertex[3 * triangles[3 * i + 1]]);
			glVertex3fv(&vertex[3 * triangles[3 * i + 2]]);
		}

	// koniec definicji obiektu
	glEnd();

	// skierowanie poleceñ do wykonania
	glFlush();

	// zamiana buforów koloru
	glutSwapBuffers();
}
Beispiel #4
0
bool Cone::Intersect(const Ray &r, float *tHit, float *rayEpsilon,
        DifferentialGeometry *dg) const {
    float phi;
    Point phit;
    // Transform _Ray_ to object space
    Ray ray;
    (*WorldToObject)(r, &ray);

    // Compute quadratic cone coefficients
    float k = radius / height;
    k = k*k;
    float A = ray.d.x * ray.d.x + ray.d.y * ray.d.y -
        k * ray.d.z * ray.d.z;
    float B = 2 * (ray.d.x * ray.o.x + ray.d.y * ray.o.y -
        k * ray.d.z * (ray.o.z-height) );
    float C = ray.o.x * ray.o.x + ray.o.y * ray.o.y -
        k * (ray.o.z -height) * (ray.o.z-height);

    // Solve quadratic equation for _t_ values
    float t0, t1;
    if (!Quadratic(A, B, C, &t0, &t1))
        return false;

    // Compute intersection distance along ray
    if (t0 > ray.maxt || t1 < ray.mint)
        return false;
    float thit = t0;
    if (t0 < ray.mint) {
        thit = t1;
        if (thit > ray.maxt) return false;
    }

    // Compute cone inverse mapping
    phit = ray(thit);
    phi = atan2f(phit.y, phit.x);
    if (phi < 0.) phi += 2.f*M_PI;

    // Test cone intersection against clipping parameters
    if (phit.z < 0 || phit.z > height || phi > phiMax) {
        if (thit == t1) return false;
        thit = t1;
        if (t1 > ray.maxt) return false;
        // Compute cone inverse mapping
        phit = ray(thit);
        phi = atan2f(phit.y, phit.x);
        if (phi < 0.) phi += 2.f*M_PI;
        if (phit.z < 0 || phit.z > height || phi > phiMax)
            return false;
    }

    // Find parametric representation of cone hit
    float u = phi / phiMax;
    float v = phit.z / height;

    // Compute cone $\dpdu$ and $\dpdv$
    Vector dpdu(-phiMax * phit.y, phiMax * phit.x, 0);
    Vector dpdv(-phit.x / (1.f - v),
                -phit.y / (1.f - v), height);

    // Compute cone $\dndu$ and $\dndv$
    Vector d2Pduu = -phiMax * phiMax *
                    Vector(phit.x, phit.y, 0.);
    Vector d2Pduv = phiMax / (1.f - v) *
                    Vector(-phit.y, -phit.x, 0.);
    Vector d2Pdvv(0, 0, 0);

    // Compute coefficients for fundamental forms
    float E = Dot(dpdu, dpdu);
    float F = Dot(dpdu, dpdv);
    float G = Dot(dpdv, dpdv);
    Vector N = Normalize(Cross(dpdu, dpdv));
    float e = Dot(N, d2Pduu);
    float f = Dot(N, d2Pduv);
    float g = Dot(N, d2Pdvv);

    // Compute $\dndu$ and $\dndv$ from fundamental form coefficients
    float invEGF2 = 1.f / (E*G - F*F);
    Normal dndu = Normal((f*F - e*G) * invEGF2 * dpdu +
                         (e*F - f*E) * invEGF2 * dpdv);
    Normal dndv = Normal((g*F - f*G) * invEGF2 * dpdu +
                         (f*F - g*E) * invEGF2 * dpdv);

    // Initialize _DifferentialGeometry_ from parametric information
    const Transform &o2w = *ObjectToWorld;
    *dg = DifferentialGeometry(o2w(phit), o2w(dpdu), o2w(dpdv),
                               o2w(dndu), o2w(dndv), u, v, this);

    // Update _tHit_ for quadric intersection
    *tHit = thit;

    // Compute _rayEpsilon_ for quadric intersection
    *rayEpsilon = 5e-4f * *tHit;
    return true;
}
void CLoad3DS::ComputeNormals(t3DModel *pModel)
{
	CVector3 vVector1, vVector2, vNormal, vPoly[3];

	// If there are no objects, we can skip this part
	if(pModel->numOfObjects <= 0)
		return;

	// What are vertex normals?  And how are they different from other normals?
	// Well, if you find the normal to a triangle, you are finding a "Face Normal".
	// If you give OpenGL a face normal for lighting, it will make your object look
	// really flat and not very round.  If we find the normal for each vertex, it makes
	// the smooth lighting look.  This also covers up blocky looking objects and they appear
	// to have more polygons than they do.    Basically, what you do is first
	// calculate the face normals, then you take the average of all the normals around each
	// vertex.  It's just averaging.  That way you get a better approximation for that vertex.

	// Go through each of the objects to calculate their normals
	for(int index = 0; index < pModel->numOfObjects; index++)
	{
		// Get the current object
		t3DObject *pObject = &(pModel->pObject[index]);

		// Here we allocate all the memory we need to calculate the normals
		CVector3 *pNormals		= new CVector3 [pObject->numOfFaces];
		CVector3 *pTempNormals	= new CVector3 [pObject->numOfFaces];
		pObject->pNormals		= new CVector3 [pObject->numOfVerts];

		// Go though all of the faces of this object
		for(int i=0; i < pObject->numOfFaces; i++)
		{												
			// To cut down LARGE code, we extract the 3 points of this face
			vPoly[0] = pObject->pVerts[pObject->pFaces[i].vertIndex[0]];
			vPoly[1] = pObject->pVerts[pObject->pFaces[i].vertIndex[1]];
			vPoly[2] = pObject->pVerts[pObject->pFaces[i].vertIndex[2]];

			// Now let's calculate the face normals (Get 2 vectors and find the cross product of those 2)

			vVector1 = Vector(vPoly[0], vPoly[2]);		// Get the vector of the polygon (we just need 2 sides for the normal)
			vVector2 = Vector(vPoly[2], vPoly[1]);		// Get a second vector of the polygon

			vNormal  = Cross(vVector1, vVector2);		// Return the cross product of the 2 vectors (normalize vector, but not a unit vector)
			pTempNormals[i] = vNormal;					// Save the un-normalized normal for the vertex normals
			vNormal  = Normalize(vNormal);				// Normalize the cross product to give us the polygons normal

			pNormals[i] = vNormal;						// Assign the normal to the list of normals
		}

		//////////////// Now Get The Vertex Normals /////////////////

		CVector3 vSum = {0.0, 0.0, 0.0};
		CVector3 vZero = vSum;
		int shared=0;

		for (int i = 0; i < pObject->numOfVerts; i++)			// Go through all of the vertices
		{
			for (int j = 0; j < pObject->numOfFaces; j++)	// Go through all of the triangles
			{												// Check if the vertex is shared by another face
				if (pObject->pFaces[j].vertIndex[0] == i || 
					pObject->pFaces[j].vertIndex[1] == i || 
					pObject->pFaces[j].vertIndex[2] == i)
				{
					vSum = AddVector(vSum, pTempNormals[j]);// Add the un-normalized normal of the shared face
					shared++;								// Increase the number of shared triangles
				}
			}      
			
			// Get the normal by dividing the sum by the shared.  We negate the shared so it has the normals pointing out.
			pObject->pNormals[i] = DivideVectorByScaler(vSum, float(-shared));

			// Normalize the normal for the final vertex normal
			pObject->pNormals[i] = Normalize(pObject->pNormals[i]);	

			vSum = vZero;									// Reset the sum
			shared = 0;										// Reset the shared
		}
	
		// Free our memory and start over on the next object
		delete [] pTempNormals;
		delete [] pNormals;
	}
}
Beispiel #6
0
/* DRAW ENEMY
*	funzione che disegna le navette nemiche caricate come obj
* 		model		modello del nemico caricato
*		pos		posizione del nemico
*		direcion (r3)	orientazione (versore direzione di movimento)	
*
*/
GLvoid drawEnemy(GLMmodel* model, Point3 pos, Point3 r3){	
	// vettore temporaneo: ci serve per definire una terna di assi ortogonali tra loro di cui uno di essi e' r3  	
	Point3 temp;
	temp.x=1;
	temp.y=1;
	temp.z=1;
	
	// CI TROVIAMO LA TERNA DI ASSI ORTOGONALI TRA LORO:	r1,r2,r3
	// normalizziamo r3, anche se dovrebbe essere gia' stato normalizzato	
	r3=Normalize(r3);
	// il prodotto esterno del vettore 'r3' per un qualsiasi vettore 'temp', mi fornisce il vettore 'r1' ortogonale a r3
	Point3 r1=Normalize(Cross(r3, temp));
	// ci troviamo il versore r2, ortogonale a 'r1' e quindi anche a 'r3'  
	Point3 r2=Normalize(Cross(r3,r1));
	
	// ci creiamo un vettore che definisce la matrice (4x4) di rototraslazione che dobbiamo applicare
	/* MATRICE DI ROTO-TRASLAZIONE
		Mappatura indici del vettore sulla matrice:
			0	1	2	3
			4	5	6	7
			8	9	10	11
			12	13	14	15
		POSIZIONI:		
			0:2 		coordinate di r1		(prime tre posizioni della prima riga)
			4:6		coordinate di r2		(prime tre posizioni della seconda riga)
			8:10		coordinate di r3		(prime tre posizioni della terza riga)
			12:14		coordinate della posizione	(prime tre posizioni della quarta riga)
			3,7,11		impostate a 0			(prime tre posizioni dell'ultima colonna)
			15		impostata a 1
	*/
	GLfloat r[16];
	r[0]=r1.x;
	r[1]=r1.y;
	r[2]=r1.z;

	r[4]=r2.x;
	r[5]=r2.y;
	r[6]=r2.z;
	
	r[8]=r3.x;
	r[9]=r3.y;
	r[10]=r3.z;
	
	r[3]=0;
	r[7]=0;
	r[11]=0;
	
	r[12]=pos.x;
	r[13]=pos.y;
	r[14]=pos.z;
	r[15]=1;	
	
	/*glDisable(GL_LIGHTING);

	glPushAttrib(GL_ALL_ATTRIB_BITS);
	glPushMatrix();

		glEnable(GL_LIGHT0);
		glEnable(GL_LIGHT1);
		glEnable(GL_LIGHT2);
		glEnable(GL_COLOR_MATERIAL);			// abilita il materiale
		glColorMaterial(GL_FRONT, GL_EMISSION);	// tipo di materiale
*/

	glPushMatrix();
		// applichiamo la roto-traslazione
		glMultMatrixf(r);
		if(!freezeShip)
			angleEnemy += 0.896000;
		glRotatef(angleEnemy, 0, 0, 1);	
		glmDraw(model, GLM_SMOOTH | GLM_MATERIAL);
		//glmDraw(model, GLM_SMOOTH|GLM_TEXTURE|GLM_MATERIAL);		
	glPopMatrix();
/*		
		glDisable(GL_COLOR_MATERIAL);			// disabilita il materiale
		glDisable(GL_LIGHT2);
		glDisable(GL_LIGHT1);
		glDisable(GL_LIGHT0);

	glPopMatrix();
	glPopAttrib();


	//glEnable(GL_LIGHTING);}
*/
}
Beispiel #7
0
///===vecfunc========== ANGLE BETWEEN A-B-C ===================///
float Angle (vec2 A, vec2 B, vec2 C) {
    vec2 Vector1 = Normalize (A-B);
    vec2 Vector2 = Normalize (C-B);
    return acosd (Vector1*Vector2);
}
Beispiel #8
0
//_________________________________________________________________________________________________
void OccupancyInTimeBins(const char* input, const char* output)
{
  timeResolutions.push_back(1);
  timeResolutions.push_back(10);
  timeResolutions.push_back(100);
  
  AliRawReader* rawReader = AliRawReader::Create(input);
  
  AliMUONRawStreamTrackerHP stream(rawReader);
  
  stream.DisableWarnings();
  stream.TryRecover(kTRUE);
  
  int numberOfUsedEvents(0);
  int numberOfBadEvents(0);
  int numberOfEvents(0);
  int numberOfPhysicsEvent(0);
  int numberOfCalibrationEvent(0);
  int numberOfEventsWithMCH(0);
  int numberOfEventsWithoutCDH(0);
  
  int runNumber(-1);
  
  time_t runStart, runEnd;
  AliMergeableCollection* hc(0x0);
  
  AliCDBManager* cdbm = AliCDBManager::Instance();
  
  if (!cdbm->IsDefaultStorageSet())
  {
    cdbm->SetDefaultStorage("local:///cvmfs/alice-ocdb.cern.ch/calibration/data/2015/OCDB");
  }
  
  cdbm->SetRun(0);
  
  AliMpCDB::LoadAll();


  while (rawReader->NextEvent() ) //&& numberOfEvents < 1000 )
  {
    rawReader->Reset();
    ++numberOfEvents;
    
    if ( !rawReader->GetDataHeader() )
    {
      ++numberOfEventsWithoutCDH;
    }
    
    if (rawReader->GetType() != AliRawEventHeaderBase::kPhysicsEvent)
    {
      if ( rawReader->GetType() == AliRawEventHeaderBase::kCalibrationEvent )
      {
        ++numberOfCalibrationEvent;
      }
      continue;
    }
    
    if (runNumber<0)
    {
      runNumber = rawReader->GetRunNumber();
      GetTimeRange(runNumber,runStart,runEnd);

      hc = new AliMergeableCollection("occ");
      
      for ( std::vector<int>::size_type is = 0; is < timeResolutions.size(); ++is )
      {
        FillCollection(*hc,runStart,runEnd,timeResolutions[is]);
      }
      
      FillNumberOfPads(*hc);
      
    }
    
    ++numberOfPhysicsEvent;
    
    if ( numberOfPhysicsEvent % 5000 == 0 )
      cout << Form("%12d events processed : %12d physics %d used ones %d bad ones [ %d with MCH information ]",
                   numberOfEvents,numberOfPhysicsEvent,numberOfUsedEvents,numberOfBadEvents,numberOfEventsWithMCH) << endl;
    
    Bool_t mchThere(kFALSE);
    
    for ( int iDDL = 0; iDDL < AliDAQ::NumberOfDdls("MUONTRK") && !mchThere; ++iDDL )
    {
      rawReader->Reset();
      rawReader->Select("MUONTRK",iDDL,iDDL);
      if (rawReader->ReadHeader() )
      {
        if (rawReader->GetEquipmentSize() ) mchThere = kTRUE;
      }
    }
    
    if ( mchThere)
    {
      ++numberOfEventsWithMCH;
    }
    else
    {
      continue;
    }
    
    Int_t buspatchId;
    UShort_t  manuId;
    UChar_t manuChannel;
    UShort_t adc;
    
    stream.First();
    
    std::map<int,int> bpValues;
    
    while ( stream.Next(buspatchId,manuId,manuChannel,adc,kTRUE) )
    {
      bpValues[buspatchId]++;
    }
    
    for ( std::map<int,int>::const_iterator it = bpValues.begin(); it != bpValues.end(); ++it )
    {
      const int& buspatchId = it->first;
      const int& bpvalue = it->second;
      
      TString bpName = Form("BP%04d",buspatchId);
      
      for ( std::vector<int>::size_type is = 0; is < timeResolutions.size(); ++is )
      {
        TH1* h = hc->Histo(Form("/BUSPATCH/HITS/%ds/%s",timeResolutions[is],bpName.Data()));
        
        if (!h)
        {
          cout << "histogram not found" << endl;
          continue;
        }
        
        h->Fill(rawReader->GetTimestamp(),bpvalue);
      }
    }
    
    for ( std::vector<int>::size_type is = 0; is < timeResolutions.size(); ++is )
    {
      TH1* h = hc->Histo(Form("Nevents%ds",timeResolutions[is]));
      
      if (!h)
      {
        cout << "histogram not found" << endl;
        continue;
      }
      
      h->Fill(rawReader->GetTimestamp());
    }
    
  }
  
  // Group BP histograms per DE then DDL then Chamber then Station
  
  for ( std::vector<int>::size_type is = 0; is < timeResolutions.size(); ++is )
  {
    GroupByDE(*hc,timeResolutions[is]);
    GroupByDDL(*hc,timeResolutions[is]);
    GroupByChamber(*hc,timeResolutions[is]);
    GroupByStation(*hc,timeResolutions[is]);
  }
  
  // make normalized versions of the histograms
  Normalize(*hc);
  
  TFile* fout = new TFile(output,"RECREATE");
  hc->Write("occ");
  delete fout;
}
Beispiel #9
0
void Vector::Right(Vector A, Vector B, Vector C)
{
	Cross(A - B, A - C);
	Normalize();
}
Beispiel #10
0
int Hull::AddContactsHullHull(Separation& sep, const Point3* pVertsA, const Point3* pVertsB,
                              const Transform& trA, const Transform& trB,const Hull& hullA,const Hull& hullB,
                              HullContactCollector* hullContactCollector)
{
    const int maxContacts = hullContactCollector->GetMaxNumContacts();

    Vector3 normalWorld = sep.m_axis;

    // edge->edge contact is always a single point
    if (sep.m_separator == Separation::kFeatureBoth)
    {
        const Hull::Edge& edgeA = hullA.GetEdge(sep.m_featureA);
        const Hull::Edge& edgeB = hullB.GetEdge(sep.m_featureB);

        float ta, tb;
        Line la(pVertsA[edgeA.m_verts[0]], pVertsA[edgeA.m_verts[1]]);
        Line lb(pVertsB[edgeB.m_verts[0]], pVertsB[edgeB.m_verts[1]]);

        Intersect(la, lb, ta, tb);

#ifdef VALIDATE_CONTACT_POINTS
        AssertPointInsideHull(contact.m_points[0].m_pos, trA, hullA);
        AssertPointInsideHull(contact.m_points[0].m_pos, trB, hullB);
#endif


        Point3 posWorld = Lerp(la.m_start, la.m_end, ta);
        float depth = -sep.m_dist;
        Vector3 tangent = Normalize(pVertsA[edgeA.m_verts[1]] - pVertsA[edgeA.m_verts[0]]);

        sep.m_contact = hullContactCollector->BatchAddContactGroup(sep,1,normalWorld,tangent,&posWorld,&depth);

    }
    // face->face contact is polygon
    else
    {
        short faceA = sep.m_featureA;
        short faceB = sep.m_featureB;

        Vector3 tangent;

        // find face of hull A that is most opposite contact axis
        // TODO: avoid having to transform planes here
        if (sep.m_separator == Separation::kFeatureB)
        {
            const Hull::Edge& edgeB = hullB.GetEdge(hullB.GetFaceFirstEdge(faceB));
            tangent = Normalize(pVertsB[edgeB.m_verts[1]] - pVertsB[edgeB.m_verts[0]]);

            Scalar dmin = Scalar::Consts::MaxValue;
            for (short face = 0; face < hullA.m_numFaces; face++)
            {
                Vector3 normal = hullA.GetPlane(face).GetNormal() * trA;
                Scalar d = Dot(normal, sep.m_axis);
                if (d < dmin)
                {
                    dmin = d;
                    faceA = face;
                }
            }
        }
        else
        {
            const Hull::Edge& edgeA = hullA.GetEdge(hullA.GetFaceFirstEdge(faceA));
            tangent = Normalize(pVertsA[edgeA.m_verts[1]] - pVertsA[edgeA.m_verts[0]]);

            Scalar dmin = Scalar::Consts::MaxValue;
            for (short face = 0; face < hullB.m_numFaces; face++)
            {
                Vector3 normal = hullB.GetPlane(face).GetNormal() * trB;
                Scalar d = Dot(normal, -sep.m_axis);
                if (d < dmin)
                {
                    dmin = d;
                    faceB = face;
                }
            }
        }

        Point3 workspace[2][Hull::kMaxVerts];

        // setup initial clip face (minimizing face from hull B)
        int numContacts = 0;
        for (short edge = hullB.GetFaceFirstEdge(faceB); edge != -1; edge = hullB.GetFaceNextEdge(faceB, edge))
            workspace[0][numContacts++] = pVertsB[ hullB.GetEdgeVertex0(faceB, edge) ];

        // clip polygon to back of planes of all faces of hull A that are adjacent to witness face
        Point3* pVtxIn = workspace[0];
        Point3* pVtxOut = workspace[1];

#if 0
        for (short edge = hullA.GetFaceFirstEdge(faceA); edge != -1; edge = hullA.GetFaceNextEdge(faceA, edge))
        {
            Plane planeA = hullA.GetPlane( hullA.GetEdgeOtherFace(edge, faceA) ) * trA;
            numContacts = ClipFace(numContacts, &pVtxIn, &pVtxOut, planeA);
        }
#else
        for (short f = 0; f < hullA.GetNumFaces(); f++)
        {
            Plane planeA = hullA.GetPlane(f) * trA;
            numContacts = ClipFace(numContacts, &pVtxIn, &pVtxOut, planeA);
        }
#endif

        // only keep points that are behind the witness face
        Plane planeA = hullA.GetPlane(faceA) * trA;

        float depths[Hull::kMaxVerts];
        int numPoints = 0;
        for (int i = 0; i < numContacts; i++)
        {
            Scalar d = Dot(planeA, pVtxIn[i]);
            if (IsNegative(d))
            {
                depths[numPoints] = (float)-d;
                pVtxIn[numPoints] = pVtxIn[i];

#ifdef VALIDATE_CONTACT_POINTS
                AssertPointInsideHull(pVtxIn[numPoints], trA, hullA);
                AssertPointInsideHull(pVtxIn[numPoints], trB, hullB);
#endif
                numPoints++;
            }
        }

        //we can also use a persistentManifold/reducer class
        // keep maxContacts points at most
        if (numPoints > 0)
        {
            if (numPoints > maxContacts)
            {
                int step = (numPoints << 8) / maxContacts;

                numPoints = maxContacts;
                for (int i = 0; i < numPoints; i++)
                {
                    int nth = (step * i) >> 8;

                    depths[i] = depths[nth];
                    pVtxIn[i] = pVtxIn[nth];


#ifdef VALIDATE_CONTACT_POINTS
                    AssertPointInsideHull(contact.m_points[i].m_pos, trA, hullA);
                    AssertPointInsideHull(contact.m_points[i].m_pos, trB, hullB);
#endif
                }
            }

            sep.m_contact = hullContactCollector->BatchAddContactGroup(sep,numPoints,normalWorld,tangent,pVtxIn,depths);

        }
        return numPoints;
    }
Beispiel #11
0
void AltJacobi::Table::operator () (unsigned k,QType result[ /* p */ ]) const
 {
  for(unsigned i=0,p=this->p; i<p ;i++) result[i]=coeff(k,i,p);
  
  Normalize(result,p);
 }
void ship::Steering()
{
	//static int i = 0;

	if ((*Target).size()-1 == 0)return;

	if (Destination > (int)((*Target).size() - 1))
	{
		Destination = 0;
	}
//	m_TopSpeed = 2.0f;
	float Speed = 0;
	 X = false;
	 Y = false;

	Vector2 TargetVector((*Target)[Destination]->m_x, (*Target)[Destination]->m_y);
	Vector2 V;
	Vector2 Pos(m_x, m_y);
	Vector2 m_force;
	Vector2 Velocity;


	V = Normalize(TargetVector - Pos) * m_TopSpeed ;

	m_force = V - Velocity;
	Velocity = Velocity + m_force;
	Pos = Pos + Velocity;

	m_x = Pos.x;
	m_y = Pos.y;

	m_angle = atan2(Velocity.x,-Velocity.y);
	m_angle *= 180 / (float)M_PI;
	m_angle -= 90;

	if (Pathing == false)
	{
		if (m_x <= (*Target)[Destination]->m_x + 10 && m_x >= (*Target)[Destination]->m_x - 10)
		{
			X = true;
		};

		if (m_y <= (*Target)[Destination]->m_y + 10 && m_y >= (*Target)[Destination]->m_y - 10)
		{
			Y = true;
		};
	}
	else
	{
		if (m_x <= (*Target)[Destination]->m_x + 5 && m_x >= (*Target)[Destination]->m_x - 5)
		{
			X = true;
		};

		if (m_y <= (*Target)[Destination]->m_y + 5 && m_y >= (*Target)[Destination]->m_y - 5)
		{
			Y = true;
		};
	};


	//m_Home = 2;
	if (Pathing == false)
	{
		if (X && Y && Destination == m_Home)
		{
			Idle = true; AtDestination = true;
		}
		else if (X && Y)
		{
			Destination = m_Home; Collect(); AtDestination = true; Hull -= 4;
		};
	}
	else if (Pathing == true)
	{
		while (true)
		{
			if (Path.size() <= 0)
			{

				return;
			}
			
			Destination = Path[0]->Index;

			if (X == true && Y == true)
			{
				Path.erase(Path.begin());
				Destination = Path[0]->Index;
				X = false;
				Y = false;
			}
			else
			{
				break;
			}

		}
	};
}
Beispiel #13
0
/**
 * Actually do the recognition using the specified language mode. If none
 * is specified, the default language model in the CubeRecoContext is used.
 * @return the sorted list of alternate answers
 * @param word_mode determines whether recognition is done as a word or a phrase
 */
WordAltList *CubeObject::Recognize(LangModel *lang_mod, bool word_mode) {
  if (char_samp_ == NULL) {
    return NULL;
  }

  // clear alt lists
  Cleanup();

  // no specified language model, use the one in the reco context
  if (lang_mod == NULL) {
    lang_mod = cntxt_->LangMod();
  }

  // normalize if necessary
  if (cntxt_->SizeNormalization()) {
    Normalize();
  }

  // assume not de-slanted by default
  deslanted_ = false;

  // create a beam search object
  if (beam_obj_ == NULL) {
    beam_obj_ = new BeamSearch(cntxt_, word_mode);
  }

  // create a cube search object
  if (srch_obj_ == NULL) {
    srch_obj_ = new CubeSearchObject(cntxt_, char_samp_);
  }

  // run a beam search against the tesslang model
  alt_list_ = beam_obj_->Search(srch_obj_, lang_mod);

  // deslant (if supported by language) and re-reco if probability is low enough
  if (cntxt_->HasItalics() == true &&
      (alt_list_ == NULL || alt_list_->AltCount() < 1 ||
       alt_list_->AltCost(0) > CubeUtils::Prob2Cost(kMinProbSkipDeslanted))) {

    if (deslanted_beam_obj_ == NULL) {
      deslanted_beam_obj_ = new BeamSearch(cntxt_);
    }

    if (deslanted_srch_obj_ == NULL) {
      deslanted_char_samp_ = char_samp_->Clone();
      if (deslanted_char_samp_ == NULL) {
        fprintf(stderr, "Cube ERROR (CubeObject::Recognize): could not "
                "construct deslanted CharSamp\n");
        return NULL;
      }

      if (deslanted_char_samp_->Deslant() == false) {
        return NULL;
      }

      deslanted_srch_obj_ = new CubeSearchObject(cntxt_, deslanted_char_samp_);
    }

    // run a beam search against the tesslang model
    deslanted_alt_list_ = deslanted_beam_obj_->Search(deslanted_srch_obj_,
                                                      lang_mod);
    // should we use de-slanted altlist?
    if (deslanted_alt_list_ != NULL &&  deslanted_alt_list_->AltCount() > 0) {
      if (alt_list_ == NULL || alt_list_->AltCount() < 1 ||
          deslanted_alt_list_->AltCost(0) < alt_list_->AltCost(0)) {
        deslanted_ = true;
        return deslanted_alt_list_;
      }
    }
  }

  return alt_list_;
}
Beispiel #14
0
void ZGameInput::Update(float fElapsed)
{
	/*
	{
		static DWORD dwLastTime = timeGetTime();

		if(timeGetTime()-dwLastTime > 10 )
		{
			dwLastTime = timeGetTime();
			{
				MTextArea *pTextArea = (MTextArea*)ZGetGameInterface()->GetIDLResource()->FindWidget("CombatChatOutputTest");
				if(pTextArea)
				{
					char szbuffer[256];
					for(int i=0;i<100;i++)
					{
						szbuffer[i]=rand()%255+1;
					}
					szbuffer[100]=0;
					pTextArea->AddText(szbuffer);
					if(pTextArea->GetLineCount()>10) pTextArea->DeleteFirstLine();
				}

			}

			{
				MTextArea *pTextArea = (MTextArea*)ZGetGameInterface()->GetIDLResource()->FindWidget("CombatChatOutput");
				if(pTextArea)
				{
					char szbuffer[256];
					for(int i=0;i<100;i++)
					{
						szbuffer[i]=rand()%255+1;
					}
					szbuffer[100]=0;
					pTextArea->AddText(szbuffer);
					if(pTextArea->GetLineCount()>10) pTextArea->DeleteFirstLine();
				}
			}
		}
	}//*/

//	if(RIsActive() && !g_pGame->IsReplay())

	//jintriple3 메모리 프록시...비트 패킹..
	const ZCharaterStatusBitPacking &uStatus = ZGetGame()->m_pMyCharacter->m_dwStatusBitPackingValue.Ref();
	ZMyCharaterStatusBitPacking & zStatus = ZGetGame()->m_pMyCharacter->m_statusFlags.Ref();


	if(RIsActive())
	{
		ZCamera* pCamera = ZGetGameInterface()->GetCamera();
		ZMyCharacter* pMyCharacter = ZGetGame()->m_pMyCharacter;
		if ((!pMyCharacter) || (!pMyCharacter->GetInitialized())) return;

		// 커서가 없는 상태에서만 카메라및 게임입력을 받는다
		if(!ZGetGameInterface()->IsCursorEnable())
		{
			{
				float fRotateX = 0;
				float fRotateY = 0;

#ifdef _DONOTUSE_DINPUT_MOUSE
				// DINPUT 을 사용하지 않는경우
				int iDeltaX, iDeltaY;

				POINT pt;
				GetCursorPos(&pt);
				ScreenToClient(g_hWnd,&pt);
				iDeltaX = pt.x-RGetScreenWidth()/2;
				iDeltaY = pt.y-RGetScreenHeight()/2;

				float fRotateStep = 0.0005f * Z_MOUSE_SENSITIVITY*10.0f;
				fRotateX = (iDeltaX * fRotateStep);
				fRotateY = (iDeltaY * fRotateStep);

#else
				// 마우스 입력 dinput 처리

				ZGetInput()->GetRotation(&fRotateX,&fRotateY);
#endif

				bool bRotateEnable=false;
				// TODO : 칼로 벽에 꽂았을때 프리카메라로 바꾸자
				if( !zStatus.m_bSkill && !uStatus.m_bWallJump && !uStatus.m_bWallJump2 && !zStatus.m_bWallHang && 
					!uStatus.m_bTumble && !uStatus.m_bBlast && !uStatus.m_bBlastStand && !uStatus.m_bBlastDrop )
					bRotateEnable=true;
				if (pMyCharacter->IsDie()) bRotateEnable = true;

				if (RIsActive())
				{
					ZCamera *pCamera = ZGetGameInterface()->GetCamera();

					pCamera->m_fAngleX += fRotateY;
					pCamera->m_fAngleZ += fRotateX;

					if(pCamera->GetLookMode()==ZCAMERA_MINIMAP) {
						pCamera->m_fAngleX=max(pi/2+.1f,pCamera->m_fAngleX);
						pCamera->m_fAngleX=min(pi-0.1f,pCamera->m_fAngleX);
					}else {
						static float lastanglex,lastanglez;
						if(bRotateEnable)
						{
							// 정밀도 유지를 위해 0~2pi 로 유지
							pCamera->m_fAngleZ = fmod(pCamera->m_fAngleZ,2*PI);
							pCamera->m_fAngleX = fmod(pCamera->m_fAngleX,2*PI);

							pCamera->m_fAngleX=max(CAMERA_ANGLEX_MIN,pCamera->m_fAngleX);
							pCamera->m_fAngleX=min(CAMERA_ANGLEX_MAX,pCamera->m_fAngleX);

							lastanglex=pCamera->m_fAngleX;
							lastanglez=pCamera->m_fAngleZ;
						}else
						{
							// 각도제한이 필요하다
							pCamera->m_fAngleX=max(CAMERA_ANGLEX_MIN,pCamera->m_fAngleX);
							pCamera->m_fAngleX=min(CAMERA_ANGLEX_MAX,pCamera->m_fAngleX);

							pCamera->m_fAngleX=max(lastanglex-pi/4.f,pCamera->m_fAngleX);
							pCamera->m_fAngleX=min(lastanglex+pi/4.f,pCamera->m_fAngleX);

							pCamera->m_fAngleZ=max(lastanglez-pi/4.f,pCamera->m_fAngleZ);
							pCamera->m_fAngleZ=min(lastanglez+pi/4.f,pCamera->m_fAngleZ);

						}
					}

					ZCombatInterface* pCombatInterface = ZGetGameInterface()->GetCombatInterface();
					if (pCombatInterface && !pCombatInterface->IsChat() &&
						(pCamera->GetLookMode()==ZCAMERA_FREELOOK || pCamera->GetLookMode()==ZCAMERA_MINIMAP))
					{

						rvector right;
						rvector forward=RCameraDirection;
						CrossProduct(&right,rvector(0,0,1),forward);
						Normalize(right);
						const rvector up = rvector(0,0,1);

						rvector accel = rvector(0,0,0);

						if(ZIsActionKeyPressed(ZACTION_FORWARD)==true)	accel+=forward;
						if(ZIsActionKeyPressed(ZACTION_BACK)==true)		accel-=forward;
						if(ZIsActionKeyPressed(ZACTION_LEFT)==true)		accel-=right;
						if(ZIsActionKeyPressed(ZACTION_RIGHT)==true)	accel+=right;
						if(ZIsActionKeyPressed(ZACTION_JUMP)==true)		accel+=up;
						if(ZIsActionKeyPressed(ZACTION_USE_WEAPON)==true)			accel-=up;

						rvector cameraMove = 
							(pCamera->GetLookMode()==ZCAMERA_FREELOOK ? 1000.f : 10000.f )		// 미니맵모드는 빨리 움직임
							* fElapsed*accel;

						rvector targetPos = pCamera->GetPosition()+cameraMove;

						// 프리룩은 충돌체크를 한다
						if(pCamera->GetLookMode()==ZCAMERA_FREELOOK)
							ZGetGame()->GetWorld()->GetBsp()->CheckWall(pCamera->GetPosition(),targetPos,ZFREEOBSERVER_RADIUS,0.f,RCW_SPHERE);
						else
						// 미니맵은 범위내에 있는지 체크한다
						{
							rboundingbox *pbb = &ZGetGame()->GetWorld()->GetBsp()->GetRootNode()->bbTree;
							targetPos.x = max(min(targetPos.x,pbb->maxx),pbb->minx);
							targetPos.y = max(min(targetPos.y,pbb->maxy),pbb->miny);

							ZMiniMap *pMinimap = ZGetGameInterface()->GetMiniMap();
							if(pMinimap)
								targetPos.z = max(min(targetPos.z,pMinimap->GetHeightMax()),pMinimap->GetHeightMin());
							else
								targetPos.z = max(min(targetPos.z,7000),2000);

							
						}

						pCamera->SetPosition(targetPos);

					}
					else if ( !ZGetGame()->IsReplay())
					{
						pMyCharacter->ProcessInput( fElapsed);
					}
				}
			}
			POINT pt={RGetScreenWidth()/2,RGetScreenHeight()/2};
			ClientToScreen(g_hWnd,&pt);
			SetCursorPos(pt.x,pt.y);

			// 대쉬 키 입력 검사
			GameCheckSequenceKeyCommand();

		}else
			pMyCharacter->ReleaseButtonState();	// 메뉴가 나왔을때는 버튼이 눌리지 않은상태로 돌려놓는다
	}
}
Beispiel #15
0
void CCamera::SetViewByMouse()
{
    POINT mousePos;									// This is a window structure that holds an X and Y
    int middleX = SCREEN_WIDTH  >> 1;				// This is a binary shift to get half the width
    int middleY = SCREEN_HEIGHT >> 1;				// This is a binary shift to get half the height
    float angleY = 0.0f;							// This is the direction for looking up or down
    float angleZ = 0.0f;							// This will be the value we need to rotate around the Y axis (Left and Right)
    static float currentRotX = 0.0f;

    // Get the mouse's current X,Y position
    GetCursorPos(&mousePos);

    // If our cursor is still in the middle, we never moved... so don't update the screen
    if( (mousePos.x == middleX) && (mousePos.y == middleY) ) return;

    // Set the mouse position to the middle of our window
    SetCursorPos(middleX, middleY);

    // Get the direction the mouse moved in, but bring the number down to a reasonable amount
    angleY = (float)( (middleX - mousePos.x) ) / 500.0f;
    angleZ = (float)( (middleY - mousePos.y) ) / 500.0f;

    static float lastRotX = 0.0f;
    lastRotX = currentRotX; // We store off the currentRotX and will use it in when the angle is capped

    // Here we keep track of the current rotation (for up and down) so that
    // we can restrict the camera from doing a full 360 loop.
    currentRotX += angleZ;

    // If the current rotation (in radians) is greater than 1.0, we want to cap it.
    if(currentRotX > 1.0f)
    {
        currentRotX = 1.0f;

        // Rotate by remaining angle if there is any
        if(lastRotX != 1.0f)
        {
            // To find the axis we need to rotate around for up and down
            // movements, we need to get a perpendicular vector from the
            // camera's view vector and up vector.  This will be the axis.
            // Before using the axis, it's a good idea to normalize it first.
            CVector3 vAxis = Cross(m_vView - m_vPosition, m_vUpVector);
            vAxis = Normalize(vAxis);

            // rotate the camera by the remaining angle (1.0f - lastRotX)
            RotateView( 1.0f - lastRotX, vAxis.x, vAxis.y, vAxis.z);
        }
    }
    // Check if the rotation is below -1.0, if so we want to make sure it doesn't continue
    else if(currentRotX < -1.0f)
    {
        currentRotX = -1.0f;

        // Rotate by the remaining angle if there is any
        if(lastRotX != -1.0f)
        {
            // To find the axis we need to rotate around for up and down
            // movements, we need to get a perpendicular vector from the
            // camera's view vector and up vector.  This will be the axis.
            // Before using the axis, it's a good idea to normalize it first.
            CVector3 vAxis = Cross(m_vView - m_vPosition, m_vUpVector);
            vAxis = Normalize(vAxis);

            // rotate the camera by ( -1.0f - lastRotX)
            RotateView( -1.0f - lastRotX, vAxis.x, vAxis.y, vAxis.z);
        }
    }
    // Otherwise, we can rotate the view around our position
    else
    {
        // To find the axis we need to rotate around for up and down
        // movements, we need to get a perpendicular vector from the
        // camera's view vector and up vector.  This will be the axis.
        // Before using the axis, it's a good idea to normalize it first.
        CVector3 vAxis = Cross(m_vView - m_vPosition, m_vUpVector);
        vAxis = Normalize(vAxis);

        // Rotate around our perpendicular axis
        RotateView(angleZ, vAxis.x, vAxis.y, vAxis.z);
    }

    // Always rotate the camera around the y-axis
    RotateView(angleY, 0, 1, 0);
}
void TrackerLinearFresnel::Evaluate( Vector3D sunVectorW, Transform parentWT0 )
{
	Vector3D i = parentWT0( sunVectorW );

	Vector3D localAxis;
	Point3D focusPoint;
	if( activeAxis.getValue() == 0 )
	{
		localAxis  =  Vector3D( 1.0, 0.0, 0.0 ) ;
		focusPoint = Point3D( 0.0, axisOrigin.getValue()[0], axisOrigin.getValue()[1] ) ;
	}
	else if( activeAxis.getValue() == 1 )
	{
		localAxis =  Vector3D( 0.0, 1.0, 0.0 );
		focusPoint = Point3D( axisOrigin.getValue()[0], 0.0, axisOrigin.getValue()[1] ) ;
	}
	else
	{
		localAxis  = Vector3D( 0.0, 0.0, 1.0 ) ;
		focusPoint = Point3D( axisOrigin.getValue()[0], axisOrigin.getValue()[1], 0.0 ) ;
	}

	Vector3D focus = Vector3D( focusPoint );
	if (typeOfAimingPoint.getValue() == 0 ) //Absolute
	{
		localAxis  = parentWT0( localAxis );
		focus = Vector3D( parentWT0( focusPoint ) );
	}


	double angle = 0.0;
	//Dawann : in a Fresnel concentrator we use the project of the sun vector on the normal plan of the axis
	//it= the projection of the sun on the normal plan of the axis...
	if( localAxis == Vector3D( 1.0, 0.0, 0.0 ) )
	{
		Vector3D r = Normalize( Vector3D( 0.0, focus.y, focus.z ) );
		Vector3D it = Normalize( Vector3D( 0.0, i.y, i.z ) );
		Vector3D n = Normalize( it + r );
		if( fabs( n.z ) > 0.0  )	angle = atan2( n.z, n.y );
	}
	else if( localAxis == Vector3D( 0.0, 1.0, 0.0 ) )
	{
		Vector3D r = Normalize( Vector3D( focus.x, 0.0, focus.z ) );
		Vector3D it = Normalize( Vector3D( i.x, 0.0, i.z ) );
		Vector3D n = Normalize( it + r );
		if( fabs( n.z ) > 0.0  )	angle = - atan2( n.z, n.x );
	}
	else
	{
		Vector3D r = Normalize( Vector3D( focus.x, focus.y, 0.0 ) );
		Vector3D it = Normalize( Vector3D( i.x, i.y, 0.0 ) );
		Vector3D n = Normalize( it + r );
		if( fabs( n.x ) > 0.0  )	angle = -atan2( n.x, n.y );
	}

	SbVec3f axis = SbVec3f( localAxis.x, localAxis.y, localAxis.z );

	SoTransform* newTransform = new SoTransform();
	newTransform->rotation.setValue( axis, angle );

	SetEngineOutput(newTransform);
}
Beispiel #17
0
VECTOR4D SinCosNormal(float x, float y, float z) {
  VECTOR4D N = { 0.3f * 3.0f * PI * sin(3.0f * x * PI) * sinf(3.0f * y * PI), -0.3f * 3.0f * PI * cosf(3.0f * x * PI) * cos(3.0f * y * PI), 1.0f, 0.0f };
  N = Normalize(N);
  return N;
}
void skiplightreweightdraw()
{
	float beta  = 0.045;//110/50 = 0.28;//FEXGSP = 0.4
	float gamma = 1.182;//110/50 = 1.24;//FEXGSP = 0.4

	auto f= new TFile("skiplightreweight.root");
	auto h12all = (TH1F *)f->Get("h12all");
	auto h12fcr = (TH1F *)f->Get("h12fcr");
	auto h12fex = (TH1F *)f->Get("h12fex");
	auto h12gsp = (TH1F *)f->Get("h12gsp");
	auto hSLall = (TH1F *)f->Get("hSLall");
	auto hSLfcr = (TH1F *)f->Get("hSLfcr");
	auto hSLfex = (TH1F *)f->Get("hSLfex");
	auto hSLgsp = (TH1F *)f->Get("hSLgsp");
	auto h12data = (TH1F *)f->Get("h12data");
	auto hSLdata = (TH1F *)f->Get("hSLdata");

	auto h12dphiall = (TH1F *)f->Get("h12dphiall");
	auto h12dphifcr = (TH1F *)f->Get("h12dphifcr");
	auto h12dphifex = (TH1F *)f->Get("h12dphifex");
	auto h12dphigsp = (TH1F *)f->Get("h12dphigsp");
	auto hSLdphiall = (TH1F *)f->Get("hSLdphiall");
	auto hSLdphifcr = (TH1F *)f->Get("hSLdphifcr");
	auto hSLdphifex = (TH1F *)f->Get("hSLdphifex");
	auto hSLdphigsp = (TH1F *)f->Get("hSLdphigsp");
	auto h12dphidata = (TH1F *)f->Get("h12dphidata");
	auto hSLdphidata = (TH1F *)f->Get("hSLdphidata");

	auto h12dphiNSall = (TH1F *)f->Get("h12dphiNSall");
	auto h12dphiNSfcr = (TH1F *)f->Get("h12dphiNSfcr");
	auto h12dphiNSfex = (TH1F *)f->Get("h12dphiNSfex");
	auto h12dphiNSgsp = (TH1F *)f->Get("h12dphiNSgsp");
	auto hSLdphiNSall = (TH1F *)f->Get("hSLdphiNSall");
	auto hSLdphiNSfcr = (TH1F *)f->Get("hSLdphiNSfcr");
	auto hSLdphiNSfex = (TH1F *)f->Get("hSLdphiNSfex");
	auto hSLdphiNSgsp = (TH1F *)f->Get("hSLdphiNSgsp");
	auto h12dphiNSdata = (TH1F *)f->Get("h12dphiNSdata");
	auto hSLdphiNSdata = (TH1F *)f->Get("hSLdphiNSdata");


	auto h12ordall = (TH1F *)f->Get("h12ordall");
	auto h12ordfcr = (TH1F *)f->Get("h12ordfcr");
	auto h12ordfex = (TH1F *)f->Get("h12ordfex");
	auto h12ordgsp = (TH1F *)f->Get("h12ordgsp");
	auto hSLordall = (TH1F *)f->Get("hSLordall");
	auto hSLordfcr = (TH1F *)f->Get("hSLordfcr");
	auto hSLordfex = (TH1F *)f->Get("hSLordfex");
	auto hSLordgsp = (TH1F *)f->Get("hSLordgsp");
	auto h12orddata = (TH1F *)f->Get("h12orddata");
	auto hSLorddata = (TH1F *)f->Get("hSLorddata");


	auto h12reweighted = (TH1F *)h12all->Clone("h12reweighted");
	auto hSLreweighted = (TH1F *)hSLall->Clone("hSLreweighted");
	h12reweighted->Reset();h12reweighted->SetTitle("h12reweighted");
	hSLreweighted->Reset();hSLreweighted->SetTitle("hSLreweighted");

	auto h12dphiNSreweighted = (TH1F *)h12dphiNSall->Clone("h12dphiNSreweighted");
	auto hSLdphiNSreweighted = (TH1F *)hSLdphiNSall->Clone("hSLdphiNSreweighted");
	h12dphiNSreweighted->Reset();h12dphiNSreweighted->SetTitle("h12dphiNSreweighted");
	hSLdphiNSreweighted->Reset();hSLdphiNSreweighted->SetTitle("hSLdphiNSreweighted");

	auto h12dphireweighted = (TH1F *)h12dphiall->Clone("h12dphireweighted");
	auto hSLdphireweighted = (TH1F *)hSLdphiall->Clone("hSLdphireweighted");
	h12dphireweighted->Reset();h12dphireweighted->SetTitle("h12dphireweighted");
	hSLdphireweighted->Reset();hSLdphireweighted->SetTitle("hSLdphireweighted");

	auto h12ordreweighted = (TH1F *)h12ordall->Clone("h12ordreweighted");
	auto hSLordreweighted = (TH1F *)hSLordall->Clone("hSLordreweighted");
	h12ordreweighted->Reset();h12ordreweighted->SetTitle("h12ordreweighted");
	hSLordreweighted->Reset();hSLordreweighted->SetTitle("hSLordreweighted");


	h12reweighted->Add(h12fex,h12gsp,beta,gamma);
	h12reweighted->Add(h12fcr);

	hSLreweighted->Add(hSLfex,hSLgsp,beta,gamma);
	hSLreweighted->Add(hSLfcr);

	h12dphireweighted->Add(h12dphifex,h12dphigsp,beta,gamma);
	h12dphireweighted->Add(h12dphifcr);

	hSLdphireweighted->Add(hSLdphifex,hSLdphigsp,beta,gamma);
	hSLdphireweighted->Add(hSLdphifcr);

	h12dphiNSreweighted->Add(h12dphiNSfex,h12dphiNSgsp,beta,gamma);
	h12dphiNSreweighted->Add(h12dphiNSfcr);

	hSLdphiNSreweighted->Add(hSLdphiNSfex,hSLdphiNSgsp,beta,gamma);
	hSLdphiNSreweighted->Add(hSLdphiNSfcr);

	h12ordreweighted->Add(h12ordfex,h12ordgsp,beta,gamma);
	h12ordreweighted->Add(h12ordfcr);

	hSLordreweighted->Add(hSLordfex,hSLordgsp,beta,gamma);
	hSLordreweighted->Add(hSLordfcr);



	Normalize({h12data,h12all,hSLdata,hSLall,
			h12dphiall,hSLdphiall,h12dphidata,hSLdphidata,
			h12dphiNSall,hSLdphiNSall,h12dphiNSdata,hSLdphiNSdata,
			h12ordall,hSLordall,h12orddata,hSLorddata});
	SetMC({h12all,hSLall,h12dphiall,hSLdphiall});

	ploteffectiveentries = false;
	plotymax = 0.12;
	plotylog = false;
	plotputmean = true;
	aktstring+="PF Jets R=0.4";
  	plotsecondline = "p_{T,1}>120GeV,p_{T,2}>30GeV";
  	plotthirdline  = "#Delta#phi>2#pi/3, CSV>0.9";
  	
  	
  	plotfilenameend = "12";
  	DrawCompare(h12data,h12all);
	plotfilenameend = "SL";
  	DrawCompare(hSLdata,hSLall);

	Normalize({h12reweighted,hSLreweighted});
	SetMC({h12reweighted,hSLreweighted});

	plotfilenameend = "12";
	DrawCompare(h12data,h12reweighted);
	plotfilenameend = "SL";
	DrawCompare(hSLdata,hSLreweighted);

	plotfilenameend = "";

	// vector<int> colors = {TColor::GetColor("#FA7200"),
	// 					  TColor::GetColor("#9ACD32"),
	// 					  TColor::GetColor("#0D98BA")};//{kGreen-9, kOrange+1,kBlue+3};

	vector<int> colors = {TColor::GetColor(25,87,5),//18,58,5),
						  TColor::GetColor(255,109,24),//234,117,1),//255,117,24),
						  TColor::GetColor(77,135,232)};//{kGreen-9, kOrange+1,kBlue+3};


	auto h12stack = stackhists({h12fcr,h12fex,h12gsp},colors,"h12stack","(P)");
	DrawCompare(h12data,h12stack,"x_{J}");


	h12fex->Scale(beta); h12gsp->Scale(gamma);
	auto h12stack2 = stackhists({h12fcr,h12fex,h12gsp},colors,"h12stack2","(W)");
	DrawCompare(h12data,h12stack2,"x_{J}");


	auto hSLstack = stackhists({hSLfcr,hSLfex,hSLgsp},colors,"hSLstack","(P)");
	DrawCompare(hSLdata,hSLstack,"x_{J}");


	hSLfex->Scale(beta); hSLgsp->Scale(gamma);
	auto hSLstack2 = stackhists({hSLfcr,hSLfex,hSLgsp},colors,"hSLstack2","(W)");
	DrawCompare(hSLdata,hSLstack2,"x_{J}");





	plotputmean = false;
	plotylog = false;
	plotymax = 1.1;
	plotymin = 1E-5;


	Normalize({hSLordreweighted,h12ordreweighted});
	SetMC({hSLordreweighted,h12ordreweighted});

	DrawCompare(h12orddata,h12ordreweighted);
	DrawCompare(hSLorddata,hSLordreweighted);

	auto h12ordstack = stackhists({h12ordfcr,h12ordfex,h12ordgsp},colors,"h12ordstack","(P)");
	DrawCompare(h12orddata,h12ordstack,"skiplight order");


	h12ordfex->Scale(beta); h12ordgsp->Scale(gamma);
	auto h12ordstack2 = stackhists({h12ordfcr,h12ordfex,h12ordgsp},colors,"h12ordstack2","(W)");
	DrawCompare(h12orddata,h12ordstack2,"skiplight order");


	auto hSLordstack = stackhists({hSLordfcr,hSLordfex,hSLordgsp},colors,"hSLordstack","(P)");
	DrawCompare(hSLorddata,hSLordstack,"skiplight order");


	hSLordfex->Scale(beta); hSLordgsp->Scale(gamma);
	auto hSLordstack2 = stackhists({hSLordfcr,hSLordfex,hSLordgsp},colors,"hSLordstack2","(W)");
	DrawCompare(hSLorddata,hSLordstack2,"skiplight order");






	plotylog = true;
	plotymin = 9999;
	plotputmean = false;
	plotputwidth = true;
	plotymax = 0.5;
	plotthirdline  = "CSV>0.9";

	DrawCompare(h12dphidata,h12dphiall,"#Delta#phi");
	DrawCompare(hSLdphidata,hSLdphiall,"#Delta#phi");


	Normalize({hSLdphireweighted,h12dphireweighted});
	SetMC({hSLdphireweighted,h12dphireweighted});

	DrawCompare(h12dphidata,h12dphireweighted,"#Delta#phi");
	DrawCompare(hSLdphidata,hSLdphireweighted,"#Delta#phi");

	//plotymax = 0.5;

	auto h12dphistack = stackhists({h12dphifcr,h12dphifex,h12dphigsp},colors,"h12dphistack","(P)");
	DrawCompare(h12dphidata,h12dphistack,"#Delta#phi");

	h12dphifex->Scale(beta); h12dphigsp->Scale(gamma);
	auto h12dphistack2 = stackhists({h12dphifcr,h12dphifex,h12dphigsp},colors,"h12dphistack2","(W)");
	DrawCompare(h12dphidata,h12dphistack2,"#Delta#phi");


	auto hSLdphistack = stackhists({hSLdphifcr,hSLdphifex,hSLdphigsp},colors,"hSLdphistack","(P)");
	DrawCompare(hSLdphidata,hSLdphistack,"#Delta#phi");

	hSLdphifex->Scale(beta); hSLdphigsp->Scale(gamma);
	auto hSLdphistack2 = stackhists({hSLdphifcr,hSLdphifex,hSLdphigsp},colors,"hSLdphistack2","(W)");
	DrawCompare(hSLdphidata,hSLdphistack2,"#Delta#phi");



	plotylog = false;
	plotymax = 0.25;
//only interesting dphi region
	DrawCompare(h12dphiNSdata,h12dphiNSall);
	DrawCompare(hSLdphiNSdata,hSLdphiNSall);


	Normalize({hSLdphiNSreweighted,h12dphiNSreweighted});
	SetMC({hSLdphiNSreweighted,h12dphiNSreweighted});

	DrawCompare(h12dphiNSdata,h12dphiNSreweighted);
	DrawCompare(hSLdphiNSdata,hSLdphiNSreweighted);



	auto h12dphiNSstack = stackhists({h12dphiNSfcr,h12dphiNSfex,h12dphiNSgsp},colors,"h12dphiNSstack","(P)");
	DrawCompare(h12dphiNSdata,h12dphiNSstack,"#Delta#phi");

	h12dphiNSfex->Scale(beta); h12dphiNSgsp->Scale(gamma);
	auto h12dphiNSstack2 = stackhists({h12dphiNSfcr,h12dphiNSfex,h12dphiNSgsp},colors,"h12dphiNSstack2","(W)");
	DrawCompare(h12dphiNSdata,h12dphiNSstack2,"#Delta#phi");


	auto hSLdphiNSstack = stackhists({hSLdphiNSfcr,hSLdphiNSfex,hSLdphiNSgsp},colors,"hSLdphiNSstack","(P)");
	DrawCompare(hSLdphiNSdata,hSLdphiNSstack,"#Delta#phi");

	hSLdphiNSfex->Scale(beta); hSLdphiNSgsp->Scale(gamma);
	auto hSLdphiNSstack2 = stackhists({hSLdphiNSfcr,hSLdphiNSfex,hSLdphiNSgsp},colors,"hSLdphiNSstack2","(W)");
	DrawCompare(hSLdphiNSdata,hSLdphiNSstack2,"#Delta#phi");



// 	int nearsidebin1 = 1;
// 	int nearsidebin2 = hSLdphifex->GetNbinsX()/3;

// 	int awaysidebin1 = hSLdphifex->GetNbinsX()/3*2;
// 	int awaysidebin2 = hSLdphifex->GetNbinsX()-1;

// 	float NnsFEX  = hSLdphifex->Integral(nearsidebin1,nearsidebin2);
// 	float NnsGSP  = hSLdphigsp->Integral(nearsidebin1,nearsidebin2);
// 	float NasFEX  = hSLdphifex->Integral(awaysidebin1,awaysidebin2);
// 	float NasGSP  = hSLdphigsp->Integral(awaysidebin1,awaysidebin2);

// 	float NnsData = hSLdphidata->Integral(nearsidebin1,nearsidebin2);
// 	float NasData = hSLdphidata->Integral(awaysidebin1,awaysidebin2);

// 	float alpha = (NnsData - NnsGSP*(1+NasFEX/NasGSP))/(NnsFEX - NnsGSP*NasFEX/NasGSP); 
// 	float beta2 = ((1-alpha)*NasFEX+NasGSP)/NasGSP;

// if (alpha<0) alpha =0;

// 	cout<<"!!!"<<alpha<<" "<<beta2<<endl;



// 	hSLdphifex->Scale(alpha); hSLdphigsp->Scale(beta2);
// 	auto hSLdphistack2_new = stackhists({hSLdphifcr,hSLdphifex,hSLdphigsp},colors,"hSLdphistack2_new");
// 	DrawCompare(hSLdphidata,hSLdphistack2_new,"#Delta#phi");


// 	cout<<" NasFEX+NasGSP = "<<NasFEX+NasGSP<<" ?= "<<
// 		hSLdphifex->Integral(awaysidebin1,awaysidebin2)+hSLdphigsp->Integral(awaysidebin1,awaysidebin2)<<endl;


// 	ploteffectiveentries = false;
// 	plotymax = 0.12;
// 	plotylog = false;
// 	plotputmean = true;
// 	aktstring+="PF Jets R=0.4";
//   	plotsecondline = "p_{T,1}>120GeV,p_{T,2}>30GeV";
//   	plotthirdline  = "#Delta#phi>2#pi/3, CSV>0.9";






// 	auto h12reweightedtwice = (TH1F *)h12all->Clone("h12reweightedtwice");
// 	auto hSLreweightedtwice = (TH1F *)hSLall->Clone("hSLreweightedtwice");
// 	h12reweightedtwice->Reset();h12reweightedtwice->SetTitle("h12reweightedtwice");
// 	hSLreweightedtwice->Reset();hSLreweightedtwice->SetTitle("hSLreweightedtwice");

// 	h12reweightedtwice->Add(h12fex,h12gsp,alpha,beta2);
// 	h12reweightedtwice->Add(h12fcr);
// 	cout<<"h12reweightedtwice "<<h12reweightedtwice->GetMean()<<endl;

// 	hSLreweightedtwice->Add(hSLfex,hSLgsp,alpha,beta2);
// 	hSLreweightedtwice->Add(hSLfcr);
// 	cout<<"hSLreweightedtwice "<<hSLreweightedtwice->GetMean()<<endl;

// 	Normalize({h12reweightedtwice,hSLreweightedtwice});
// 	SetMC({h12reweightedtwice,hSLreweightedtwice});

// 	plotfilenameend = "12";
// 	DrawCompare(h12data,h12reweightedtwice);
// 	plotfilenameend = "SL";
// 	DrawCompare(hSLdata,hSLreweightedtwice);
// 	plotfilenameend="";



// 	hSLfex->Scale(alpha); hSLgsp->Scale(beta2);
// 	auto hSLstack2_new = stackhists({hSLfcr,hSLfex,hSLgsp},colors,"hSLstack2_new");
// 	DrawCompare(hSLdata,hSLstack2_new,"x_{J}");

// 	h12fex->Scale(alpha); h12gsp->Scale(beta2);
// 	auto h12stack2_new = stackhists({h12fcr,h12fex,h12gsp},colors,"h12stack2_new");
// 	DrawCompare(h12data,h12stack2_new,"x_{J}","___");






}
Beispiel #19
0
/* DRAW POLICE
*	funzione che disegna le navette nemiche caricate come obj
* 		model		modello del nemico caricato
*		pos		posizione del nemico
*		direcion (r1)	orientazione (versore direzione di movimento)	
*
*/
GLvoid drawPolice(GLMmodel* model, Point3 pos, Point3 r1){
	// vettore temporaneo: ci serve per definire una terna di assi ortogonali tra loro di cui uno di essi e' r3  	
	Point3 temp;
	temp.x=1;
	temp.y=1;
	temp.z=1;
	
	// CI TROVIAMO LA TERNA DI ASSI ORTOGONALI TRA LORO:	r1,r2,r3
	// normalizziamo r1, anche se dovrebbe essere gia' stato normalizzato	
	r1=Normalize(r1);
	// il prodotto esterno del vettore 'r1' per un qualsiasi vettore 'temp', mi fornisce il vettore 'r2' ortogonale a r1
	Point3 r2=Normalize(Cross(r1, temp));
	// ci troviamo il versore r3, ortogonale a 'r2' e quindi anche a 'r1'  
	Point3 r3=Normalize(Cross(r1,r2));
	
	// ci creiamo un vettore che definisce la matrice (4x4) di rototraslazione che dobbiamo applicare
	/* MATRICE DI ROTO-TRASLAZIONE
		Mappatura indici del vettore sulla matrice:
			0	1	2	3
			4	5	6	7
			8	9	10	11
			12	13	14	15
		POSIZIONI:		
			0:2 		coordinate di r1		(prime tre posizioni della prima riga)
			4:6			coordinate di r2		(prime tre posizioni della seconda riga)
			8:10		coordinate di r3		(prime tre posizioni della terza riga)
			12:14		coordinate della posizione	(prime tre posizioni della quarta riga)
			3,7,11		impostate a 0			(prime tre posizioni dell'ultima colonna)
			15			impostata a 1
	*/
	GLfloat r[16];
	r[0]=r1.x;
	r[1]=r1.y;
	r[2]=r1.z;

	r[4]=r2.x;
	r[5]=r2.y;
	r[6]=r2.z;
	
	r[8]=r3.x;
	r[9]=r3.y;
	r[10]=r3.z;
	
	r[3]=0;
	r[7]=0;
	r[11]=0;
	
	r[12]=pos.x;
	r[13]=pos.y;
	r[14]=pos.z;
	r[15]=1;	
		
	glPushMatrix();
		glMultMatrixf(r);
		//printf("diff=%f\n", (glutGet(GLUT_ELAPSED_TIME)-anglePolice)*0.032); fflush(stdout);
		// se non sono nel freeze		
		if(!freezeShip)
			anglePolice += 0.896000;
		glRotatef(anglePolice, 1, 0, 0);
		//ROTAZIONE perche' stia dritto:		
		//glRotatef(-135, 1, 0, 0);
		glmDraw(model, GLM_SMOOTH | GLM_MATERIAL);	
		//glmDraw(model, GLM_SMOOTH|GLM_TEXTURE|GLM_MATERIAL);		
	glPopMatrix();
}
Beispiel #20
0
Point Sphere::Sample(float u1, float u2, Normal *ns) const {
    Point p = Point(0,0,0) + radius * UniformSampleSphere(u1, u2);
    *ns = Normalize((*ObjectToWorld)(Normal(p.x, p.y, p.z)));
    if (ReverseOrientation) *ns *= -1.f;
    return (*ObjectToWorld)(p);
}
Beispiel #21
0
float Angle (vec3 A, vec3 B, vec3 C) {
    vec3 Vector1 = Normalize (A-B);
    vec3 Vector2 = Normalize (C-B);
    return acosd (Vector1*Vector2);
}
Beispiel #22
0
bool Sphere::Intersect(const Ray &r, float *tHit, float *rayEpsilon,
                       DifferentialGeometry *dg) const {
    float phi;
    Point phit;
    // Transform _Ray_ to object space
    Ray ray;
    (*WorldToObject)(r, &ray);

    // Compute quadratic sphere coefficients
    float A = ray.d.x*ray.d.x + ray.d.y*ray.d.y + ray.d.z*ray.d.z;
    float B = 2 * (ray.d.x*ray.o.x + ray.d.y*ray.o.y + ray.d.z*ray.o.z);
    float C = ray.o.x*ray.o.x + ray.o.y*ray.o.y +
              ray.o.z*ray.o.z - radius*radius;

    // Solve quadratic equation for _t_ values
    float t0, t1;
    if (!Quadratic(A, B, C, &t0, &t1))
        return false;

    // Compute intersection distance along ray
    if (t0 > ray.maxt || t1 < ray.mint)
        return false;
    float thit = t0;
    if (t0 < ray.mint) {
        thit = t1;
        if (thit > ray.maxt) return false;
    }

    // Compute sphere hit position and $\phi$
    phit = ray(thit);
    if (phit.x == 0.f && phit.y == 0.f) phit.x = 1e-5f * radius;
    phi = atan2f(phit.y, phit.x);
    if (phi < 0.) phi += 2.f*M_PI;

    // Test sphere intersection against clipping parameters
    if ((zmin > -radius && phit.z < zmin) ||
        (zmax <  radius && phit.z > zmax) || phi > phiMax) {
        if (thit == t1) return false;
        if (t1 > ray.maxt) return false;
        thit = t1;
        // Compute sphere hit position and $\phi$
        phit = ray(thit);
        if (phit.x == 0.f && phit.y == 0.f) phit.x = 1e-5f * radius;
        phi = atan2f(phit.y, phit.x);
        if (phi < 0.) phi += 2.f*M_PI;
        if ((zmin > -radius && phit.z < zmin) ||
            (zmax <  radius && phit.z > zmax) || phi > phiMax)
            return false;
    }

    // Find parametric representation of sphere hit
    float u = phi / phiMax;
    float theta = acosf(Clamp(phit.z / radius, -1.f, 1.f));
    float v = (theta - thetaMin) / (thetaMax - thetaMin);

    // Compute sphere $\dpdu$ and $\dpdv$
    float zradius = sqrtf(phit.x*phit.x + phit.y*phit.y);
    float invzradius = 1.f / zradius;
    float cosphi = phit.x * invzradius;
    float sinphi = phit.y * invzradius;
    Vector dpdu(-phiMax * phit.y, phiMax * phit.x, 0);
    Vector dpdv = (thetaMax-thetaMin) *
        Vector(phit.z * cosphi, phit.z * sinphi,
               -radius * sinf(theta));

    // Compute sphere $\dndu$ and $\dndv$
    Vector d2Pduu = -phiMax * phiMax * Vector(phit.x, phit.y, 0);
    Vector d2Pduv = (thetaMax - thetaMin) * phit.z * phiMax *
                    Vector(-sinphi, cosphi, 0.);
    Vector d2Pdvv = -(thetaMax - thetaMin) * (thetaMax - thetaMin) *
                    Vector(phit.x, phit.y, phit.z);

    // Compute coefficients for fundamental forms
    float E = Dot(dpdu, dpdu);
    float F = Dot(dpdu, dpdv);
    float G = Dot(dpdv, dpdv);
    Vector N = Normalize(Cross(dpdu, dpdv));
    float e = Dot(N, d2Pduu);
    float f = Dot(N, d2Pduv);
    float g = Dot(N, d2Pdvv);

    // Compute $\dndu$ and $\dndv$ from fundamental form coefficients
    float invEGF2 = 1.f / (E*G - F*F);
    Normal dndu = Normal((f*F - e*G) * invEGF2 * dpdu +
                         (e*F - f*E) * invEGF2 * dpdv);
    Normal dndv = Normal((g*F - f*G) * invEGF2 * dpdu +
                         (f*F - g*E) * invEGF2 * dpdv);

    // Initialize _DifferentialGeometry_ from parametric information
    const Transform &o2w = *ObjectToWorld;
    *dg = DifferentialGeometry(o2w(phit), o2w(dpdu), o2w(dpdv),
                               o2w(dndu), o2w(dndv), u, v, this);

    // Update _tHit_ for quadric intersection
    *tHit = thit;

    // Compute _rayEpsilon_ for quadric intersection
    *rayEpsilon = 5e-4f * *tHit;
    return true;
}
void TestLinAlg()
{
    // Instantiate templates, check sizes, make sure operators compile etc.

    static_assert(sizeof(Vec2f)     == 8  , "Vec2f size test failed"    );
    static_assert(sizeof(Vec3f)     == 12 , "Vec3f size test failed"    );
    static_assert(sizeof(Vec4f)     == 16 , "Vec4f size test failed"    );
    static_assert(sizeof(Vec2d)     == 16 , "Vec2d size test failed"    );
    static_assert(sizeof(Vec3d)     == 24 , "Vec3d size test failed"    );
    static_assert(sizeof(Vec4d)     == 32 , "Vec4d size test failed"    );
    static_assert(sizeof(Vec2i)     == 8  , "Vec2i size test failed"    );
    static_assert(sizeof(Vec3i)     == 12 , "Vec3i size test failed"    );
    static_assert(sizeof(Vec4i)     == 16 , "Vec4i size test failed"    );
    static_assert(sizeof(Vec2ui)    == 8  , "Vec2ui size test failed"   );
    static_assert(sizeof(Vec3ui)    == 12 , "Vec3ui size test failed"   );
    static_assert(sizeof(Vec4ui)    == 16 , "Vec4ui size test failed"   );
    static_assert(sizeof(Matrix44f) == 64 , "Matrix44f size test failed");
    static_assert(sizeof(Matrix44d) == 128, "Matrix44d size test failed");

    Vec2f vec2f(0.0f, 0.0f);
    Vec3f vec3f(0.0f, 0.0f, 0.0f);
    Vec4f vec4f(0.0f, 0.0f, 0.0f, 0.0f);
    Vec2d vec2d(0.0, 0.0);
    Vec3d vec3d(0.0, 0.0, 0.0);
    Vec4d vec4d(0.0, 0.0, 0.0, 0.0);
    Vec2i vec2i(-1, -1);
    Vec3i vec3i(-1, -1, -1);
    Vec4i vec4i(-1, -1, -1, -1);
    Vec2ui vec2ui(0, 0);
    Vec3ui vec3ui(0, 0, 0);
    Vec4ui vec4ui(0, 0, 0, 0);
    float f = 0.0f;
    bool b = false;

    b = (vec3f == vec3f);
    b = (vec3f != vec3f);
    vec3f = Vec3f(1.0f) + Vec3f(2.0f);
    vec3f = Vec3f(1.0f) - Vec3f(2.0f);
    vec3f = Vec3f(1.0f) * Vec3f(2.0f);
    vec3f = Vec3f(1.0f) / Vec3f(2.0f);
    vec3f = Vec3f(1.0f) * f;
    vec3f = f * Vec3f(1.0f);
    vec3f = Vec3f(1.0f) / f;
    vec3f = -Vec3f(1.0f);
    vec3f += Vec3f(1.0f);
    vec3f -= Vec3f(1.0f);
    vec3f *= Vec3f(1.0f);
    vec3f /= Vec3f(1.0f);
    vec3f *= f;
    vec3f /= f;
    f = vec3f[0];
    vec3f[0] = f;
    f = Length(vec3f);
    f = LengthSquared(vec3f);
    vec3f = Normalize(vec3f);
    f = Dot(Vec3f(1.0f), Vec3f(2.0f));
    vec3f = Vec3f(1.0f) ^ Vec3f(2.0f);

    Matrix44f matf;
    matf.Identity();
    Matrix44d matd;
    matf.RotationX(1);
    matf.RotationY(1);
    matf.RotationZ(1);
    matf.Scaling(1);
    b = matf == matf;
    matf = matf * matf;
    matf.BuildLookAtMatrix(Vec3f(0.0f, 10.0f, 10.0f), Vec3f(0.0f));
    matf.BuildProjection(90.0f, 4.0f / 3.0f, 1.0f, 1000.0f);
    Vec3f out;
    matf.Transf3x3(vec3f, out);
    matf.Transf4x4(vec3f, out);
    matf.Transpose3x3();
    matf.Transpose4x4();
    matf.Invert();
}
Beispiel #24
0
/////////////////////////////////////////////////////////////////
// JPE: Cargar Vertices
/////////////////////////////////////////////////////////////////
void LoadVertices(SimpleVertex** verticesDest, WORD** indicesDest, int* cantVertices, int* cantIndices )
{
	SimpleVertex* vertices = new SimpleVertex[24]();
	*(verticesDest) = vertices;
	*(cantVertices) = 24;

	// CARA ARRIBA
	vertices[0] = { XMFLOAT3(-1.0f, 1.0f, -1.0f), XMFLOAT4(0.0f, 0.0f, 1.0f, 1.0f), XMFLOAT2(0.0f, 1.0f), XMFLOAT3(0.0f, 1.0f, 0.0f) }; // 0 
	vertices[1] = { XMFLOAT3(1.0f, 1.0f, -1.0f), XMFLOAT4(0.0f, 1.0f, 0.0f, 1.0f), XMFLOAT2(1.0f, 1.0f), XMFLOAT3(0.0f, 1.0f, 0.0f) }; // 1
	vertices[2] = { XMFLOAT3(1.0f, 1.0f, 1.0f), XMFLOAT4(0.0f, 1.0f, 1.0f, 1.0f), XMFLOAT2(1.0f, 0.0f), XMFLOAT3(0.0f, 1.0f, 0.0f) }; // 2	
	vertices[3] = { XMFLOAT3(-1.0f, 1.0f, 1.0f), XMFLOAT4(1.0f, 0.0f, 0.0f, 1.0f), XMFLOAT2(0.0f, 0.0f), XMFLOAT3(0.0f, 1.0f, 0.0f) }; // 3	
	// CARA ABAJO
	vertices[4] = { XMFLOAT3(-1.0f, -1.0f, -1.0f), XMFLOAT4(1.0f, 0.0f, 1.0f, 1.0f), XMFLOAT2(0.0f, 0.0f), XMFLOAT3(0.0f, -1.0f, 0.0f) }; // 4
	vertices[5] = { XMFLOAT3(1.0f, -1.0f, -1.0f), XMFLOAT4(1.0f, 1.0f, 0.0f, 1.0f), XMFLOAT2(1.0f, 0.0f), XMFLOAT3(0.0f, -1.0f, 0.0f) }; // 5
	vertices[6] = { XMFLOAT3(1.0f, -1.0f, 1.0f), XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f), XMFLOAT2(1.0f, 1.0f), XMFLOAT3(0.0f, -1.0f, 0.0f) }; // 6
	vertices[7] = { XMFLOAT3(-1.0f, -1.0f, 1.0f), XMFLOAT4(0.0f, 0.0f, 0.0f, 1.0f), XMFLOAT2(0.0f, 1.0f), XMFLOAT3(0.0f, -1.0f, 0.0f) }; // 7
	// CARA FRENTE
	vertices[8] = { XMFLOAT3(-1.0f, 1.0f, -1.0f), XMFLOAT4(0.0f, 0.0f, 1.0f, 1.0f), XMFLOAT2(0.0f, 0.0f), XMFLOAT3(0.0f, 0.0f, -1.0f) }; // 0
	vertices[9] = { XMFLOAT3(1.0f, 1.0f, -1.0f), XMFLOAT4(0.0f, 1.0f, 0.0f, 1.0f), XMFLOAT2(1.0f, 0.0f), XMFLOAT3(0.0f, 0.0f, -1.0f) }; // 1
	vertices[10] = { XMFLOAT3(1.0f, -1.0f, -1.0f), XMFLOAT4(1.0f, 1.0f, 0.0f, 1.0f), XMFLOAT2(1.0f, 1.0f), XMFLOAT3(0.0f, 0.0f, -1.0f) }; // 5
	vertices[11] = { XMFLOAT3(-1.0f, -1.0f, -1.0f), XMFLOAT4(1.0f, 0.0f, 1.0f, 1.0f), XMFLOAT2(0.0f, 1.0f), XMFLOAT3(0.0f, 0.0f, -1.0f) }; // 4
	// CARA DORSO
	vertices[12] = { XMFLOAT3(1.0f, 1.0f, 1.0f), XMFLOAT4(0.0f, 1.0f, 1.0f, 1.0f), XMFLOAT2(0.0f, 0.0f), XMFLOAT3(0.0f, 0.0f, 1.0f) }; // 2		
	vertices[13] = { XMFLOAT3(-1.0f, 1.0f, 1.0f), XMFLOAT4(1.0f, 0.0f, 0.0f, 1.0f), XMFLOAT2(1.0f, 0.0f), XMFLOAT3(0.0f, 0.0f, 1.0f) }; // 3	
	vertices[14] = { XMFLOAT3(-1.0f, -1.0f, 1.0f), XMFLOAT4(0.0f, 0.0f, 0.0f, 1.0f), XMFLOAT2(1.0f, 1.0f), XMFLOAT3(0.0f, 0.0f, 1.0f) }; // 7	
	vertices[15] = { XMFLOAT3(1.0f, -1.0f, 1.0f), XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f), XMFLOAT2(0.0f, 1.0f), XMFLOAT3(0.0f, 0.0f, 1.0f) }; // 6	
	// CARA DERECHA
	vertices[16] = { XMFLOAT3(1.0f, 1.0f, -1.0f), XMFLOAT4(0.0f, 1.0f, 0.0f, 1.0f), XMFLOAT2(0.0f, 0.0f), XMFLOAT3(1.0f, 0.0f, 0.0f) }; // 1	
	vertices[17] = { XMFLOAT3(1.0f, 1.0f, 1.0f), XMFLOAT4(0.0f, 1.0f, 1.0f, 1.0f), XMFLOAT2(1.0f, 0.0f), XMFLOAT3(1.0f, 0.0f, 0.0f) }; // 2		
	vertices[18] = { XMFLOAT3(1.0f, -1.0f, 1.0f), XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f), XMFLOAT2(1.0f, 1.0f), XMFLOAT3(1.0f, 0.0f, 0.0f) }; // 6	
	vertices[19] = { XMFLOAT3(1.0f, -1.0f, -1.0f), XMFLOAT4(1.0f, 1.0f, 0.0f, 1.0f), XMFLOAT2(0.0f, 1.0f), XMFLOAT3(1.0f, 0.0f, 0.0f) }; // 5	
	// CARA IZQUIERDA
	vertices[20] = { XMFLOAT3(-1.0f, 1.0f, 1.0f), XMFLOAT4(1.0f, 0.0f, 0.0f, 1.0f), XMFLOAT2(0.0f, 0.0f), XMFLOAT3(-1.0f, 0.0f, 0.0f) }; // 3	
	vertices[21] = { XMFLOAT3(-1.0f, 1.0f, -1.0f), XMFLOAT4(0.0f, 0.0f, 1.0f, 1.0f), XMFLOAT2(1.0f, 0.0f), XMFLOAT3(-1.0f, 0.0f, 0.0f) }; // 0	
	vertices[22] = { XMFLOAT3(-1.0f, -1.0f, -1.0f), XMFLOAT4(1.0f, 0.0f, 1.0f, 1.0f), XMFLOAT2(1.0f, 1.0f), XMFLOAT3(-1.0f, 0.0f, 0.0f) }; // 4	
	vertices[23] = { XMFLOAT3(-1.0f, -1.0f, 1.0f), XMFLOAT4(0.0f, 0.0f, 0.0f, 1.0f), XMFLOAT2(0.0f, 1.0f), XMFLOAT3(-1.0f, 0.0f, 0.0f) }; // 7	

	// Create index buffer
	int cantInd = 36;
	*(cantIndices) = cantInd;
	
	const WORD indices[] =
	{
		// ARRIBA
		3,2,1,
		3,1,0,
		// ABAJO
		4,5,6,
		4,6,7,
		// FRENTE
		8,9,10,
		8,10,11,
		// DORSO
		12,13,14,
		12,14,15,
		// DERECHA
		16,17,18,
		16,18,19,
		// IZQUIERDA
		20,21,22,
		20,22,23,
	};

	*(indicesDest) = new WORD[cantInd];
	memcpy(*(indicesDest), (void*)indices, cantInd * sizeof(WORD));

	//JPE: Calculo de normales, tangentes y binormales.
	for (int cara = 0; cara < 6; cara++)
	{
		for (int trig = 0; trig < 2; trig++)
		{
			int idx0 = cara * 6 + trig * 3;
			int idx1 = idx0 + 1, idx2 = idx0 + 2;

			SimpleVertex& vt0 = vertices[indices[idx0]];
			SimpleVertex& vt1 = vertices[indices[idx1]];
			SimpleVertex& vt2 = vertices[indices[idx2]];

			XMFLOAT3 p0 = vt0.Pos;
			XMFLOAT3 p1 = vt1.Pos;
			XMFLOAT3 p2 = vt2.Pos;

			XMFLOAT2 t0 = vt0.texture;
			XMFLOAT2 t1 = vt1.texture;
			XMFLOAT2 t2 = vt2.texture;

			XMFLOAT3 Edge1 = XMFLOAT3(p1.x - p0.x, p1.y - p0.y, p1.z - p0.z);
			XMFLOAT3 Edge2 = XMFLOAT3(p2.x - p0.x, p2.y - p0.y, p2.z - p0.z);

			float DeltaU1 = t1.x - t0.x;
			float DeltaV1 = t1.y - t0.y;
			float DeltaU2 = t2.x - t0.x;
			float DeltaV2 = t2.y - t0.y;

			float f = 1.0f / (DeltaU1 * DeltaV2 - DeltaU2 * DeltaV1);

			XMFLOAT3 Tangent, Bitangent;

			Tangent.x = f * (DeltaV2 * Edge1.x - DeltaV1 * Edge2.x);
			Tangent.y = f * (DeltaV2 * Edge1.y - DeltaV1 * Edge2.y);
			Tangent.z = f * (DeltaV2 * Edge1.z - DeltaV1 * Edge2.z);

			Bitangent.x = f * (-DeltaU2 * Edge1.x - DeltaU1 * Edge2.x);
			Bitangent.y = f * (-DeltaU2 * Edge1.y - DeltaU1 * Edge2.y);
			Bitangent.z = f * (-DeltaU2 * Edge1.z - DeltaU1 * Edge2.z);

			Normalize(&Tangent);
			Normalize(&Bitangent);

			vt0.Tangent = Tangent;
			vt1.Tangent = Tangent;
			vt2.Tangent = Tangent;

			vt0.Binormal = Bitangent;
			vt1.Binormal = Bitangent;
			vt2.Binormal = Bitangent;

		}
	}

}
void ResolveCollision(float coefficientOfRestitution,
                      const Sphere& sphere1, const Sphere& sphere2, const FVector3& collisionPoint,
                      const FVector3& impulseDirection, MotionProperties& motionProperties1, MotionProperties& motionProperties2)
{
#define CLAMP_RESOLVED_SPEEDS

   Sphere boundingSpheres[2] = {sphere1, sphere2};

   //static const float_t coefficientOfRestitution = -0.3f; // completely elastic

   //a) compute velocities at the point of contact

   bool hasAngularComponent[2] = { ( FNotZero<float>(motionProperties1.speed) && !ApproximatelyEqual(motionProperties1.rotation, Vec3D::ZeroVector()) ),
                                   ( FNotZero<float>(motionProperties2.speed) && !ApproximatelyEqual(motionProperties2.rotation, Vec3D::ZeroVector()) ) };

   FVector3 contactVectors[2] = { collisionPoint - boundingSpheres[0].center, collisionPoint - boundingSpheres[1].center };

   FVector3 velocities[2] = { motionProperties1.direction * motionProperties1.speed, motionProperties2.direction * motionProperties2.speed };

   FVector3 angularVelocities[2] = { motionProperties1.rotation * motionProperties1.angularSpeed, motionProperties2.rotation * motionProperties2.angularSpeed};

   FVector3 contactVelocities[2] = { velocities[0] + (hasAngularComponent[0] ? Cross(angularVelocities[0], contactVectors[0]) : Vec3D::ZeroVector()),
                                     velocities[1] + (hasAngularComponent[1] ? Cross(angularVelocities[1], contactVectors[1]) : Vec3D::ZeroVector()) };

   //b) compute inverses of inertia tensors

   //For now, use spheres as approximations. The inertia tensor for a sphere is:
   //
   //[ (2/5)mr^2       0          0     ]
   //[      0     (2/5)mr^2       0     ]
   //[      0          0     (2/5)mr^2  ]
   //
   //where the inverse is:
   //
   //[ 5 / (2 * mr^2)        0               0         ]
   //[       0         5 / (2 * mr^2)        0         ]
   //[       0               0         5 / (2 * mr^2)  ]

   float masses[2] = { boundingSpheres[0].Volume(), boundingSpheres[1].Volume() }; //assume density of asteroid is 1 Kg per cubic metre

   Matrix<float> inertiaTensorInverses[2] = {Matrix<float>(3, 3), Matrix<float>(3, 3)};

   for (int asteroidIndex = 0; asteroidIndex < 2; ++asteroidIndex)
   {
      float inertiaTensorInverseVal = 5.0f / (2.0f * masses[asteroidIndex] * boundingSpheres[asteroidIndex].radius * boundingSpheres[asteroidIndex].radius);

      inertiaTensorInverses[asteroidIndex](0, 0) = inertiaTensorInverseVal;
      inertiaTensorInverses[asteroidIndex](1, 1) = inertiaTensorInverseVal;
      inertiaTensorInverses[asteroidIndex](2, 2) = inertiaTensorInverseVal;
   }

   //c) determine direction of impulse

   //TODO: improve this

   //Vector3 impulseDirection = -contactVectors[1];
   
   //Vector3 impulseDirection = boundingSpheres[1].center - boundingSpheres[0].center;

   //impulseDirection.normalize();

   //NOTE: For the subsequent steps to work, the impulse direction must be from asteroid1 towards asteroid2

   //d) determine the impulse magnitude

   FVector3 crossA = Cross(contactVectors[0], impulseDirection);
   FVector3 multA = inertiaTensorInverses[0] * std::vector<float>{crossA.x, crossA.y, crossA.z};

   FVector3 crossB = Cross(contactVectors[1], impulseDirection);
   FVector3 multB = inertiaTensorInverses[1] * std::vector<float>{crossB.x, crossB.y, crossB.z};

   float impulseMagnitudeDenominator = (1.0f / masses[0]) + (1.0f / masses[1]) + Dot(Cross(multA, contactVectors[0]) + Cross(multB, contactVectors[1]), impulseDirection);

   float impulseMagnitude =  ( Dot(-(1 + coefficientOfRestitution) * (contactVelocities[1] - contactVelocities[0]), impulseDirection) ) / impulseMagnitudeDenominator;

   //e) compute reaction impulse vector

   FVector3 impulseVector = impulseMagnitude * impulseDirection;

   //f) compute new linear velocities

#ifdef CLAMP_RESOLVED_SPEEDS
   float minSpeed = std::min(motionProperties1.speed, motionProperties2.speed);
   float maxSpeed = std::max(motionProperties1.speed, motionProperties2.speed);
   //float_t maxSpeed = maxResolvedSpeed;
   float minRotationSpeed = std::min(motionProperties1.angularSpeed, motionProperties2.angularSpeed);
   float maxRotationSpeed = std::max(motionProperties1.angularSpeed, motionProperties2.angularSpeed);
#endif

   motionProperties1.direction = velocities[0] - (impulseVector / masses[0]);
   motionProperties1.speed = Norm(motionProperties1.direction);

#ifdef CLAMP_RESOLVED_SPEEDS
   if (FGreater<float>(motionProperties1.speed, maxSpeed))
   {
      motionProperties1.speed = maxSpeed;
   }
   else if (FLess<float>(motionProperties1.speed, minSpeed))
   {
      motionProperties1.speed = minSpeed;
   }
#endif

   Normalize(motionProperties1.direction);

   motionProperties2.direction = velocities[1] + (impulseVector / masses[1]);
   motionProperties2.speed = Norm(motionProperties2.direction);

#ifdef CLAMP_RESOLVED_SPEEDS
   if (FGreater<float>(motionProperties2.speed, maxSpeed))
   {
      motionProperties2.speed = maxSpeed;
   }
   else if (FLess<float>(motionProperties2.speed, minSpeed))
   {
      motionProperties2.speed = minSpeed;
   }
#endif
      
   Normalize(motionProperties2.direction);

   //g) compute new angular velocities

   motionProperties1.rotation = angularVelocities[0] - impulseMagnitude * ( multA );
   motionProperties1.angularSpeed = Norm(motionProperties1.rotation);
 
#ifdef CLAMP_RESOLVED_SPEEDS
   if (FGreater<float>(motionProperties1.angularSpeed, maxRotationSpeed))
   {
      motionProperties1.angularSpeed = maxRotationSpeed;
   }
   else if (FLess<float>(motionProperties1.angularSpeed, minRotationSpeed))
   {
      motionProperties1.angularSpeed = minRotationSpeed;
   }
#endif

   Normalize(motionProperties1.rotation);

   motionProperties2.rotation = angularVelocities[1] + impulseMagnitude * ( multB );
   motionProperties2.angularSpeed = Norm(motionProperties2.rotation);

#ifdef CLAMP_RESOLVED_SPEEDS
   if (FGreater<float>(motionProperties2.angularSpeed, maxRotationSpeed))
   {
      motionProperties2.angularSpeed = maxRotationSpeed;
   }
   else if (FLess<float>(motionProperties2.angularSpeed, minRotationSpeed))
   {
      motionProperties2.angularSpeed = minRotationSpeed;
   }
#endif

   Normalize(motionProperties2.rotation);
}
Beispiel #26
0
Spectrum MetropolisRenderer::Lbidir(const Scene *scene,
        const PathVertex *cameraPath, int cameraPathLength,
        const PathVertex *lightPath, int lightPathLength,
        MemoryArena &arena, const vector<LightingSample> &samples,
        RNG &rng, float time, const Distribution1D *lightDistribution,
        const RayDifferential &eRay, const Spectrum &eAlpha) const {
    PBRT_MLT_STARTED_LBIDIR();
    Spectrum L = 0.;
    bool previousSpecular = true, allSpecular = true;
    // Compute number of specular vertices for each path length
    int nVerts = cameraPathLength + lightPathLength + 2;
    int *nSpecularVertices = ALLOCA(int, nVerts);
    memset(nSpecularVertices, 0, nVerts * sizeof(int));
    for (int i = 0; i < cameraPathLength; ++i)
        for (int j = 0; j < lightPathLength; ++j)
            if (cameraPath[i].specularBounce || lightPath[j].specularBounce)
                ++nSpecularVertices[i+j+2];
    for (int i = 0; i < cameraPathLength; ++i) {
        // Initialize basic variables for camera path vertex
        const PathVertex &vc = cameraPath[i];
        const Point &pc = vc.bsdf->dgShading.p;
        const Normal &nc = vc.bsdf->dgShading.nn;

        // Compute reflected light at camera path vertex

        // Add emitted light from vertex if appropriate
        if (previousSpecular && (directLighting == NULL || !allSpecular))
            L += vc.alpha * vc.isect.Le(vc.wPrev);

        // Compute direct illumination for Metropolis path vertex
        Spectrum Ld(0.f);
        if (directLighting == NULL || !allSpecular) {
            // Choose light and call _EstimateDirect()_ for Metropolis vertex
            const LightingSample &ls = samples[i];
            float lightPdf;
            uint32_t lightNum = lightDistribution->SampleDiscrete(ls.lightNum,
                                                                  &lightPdf);
            const Light *light = scene->lights[lightNum];
            PBRT_MLT_STARTED_ESTIMATE_DIRECT();
            
            Ld = vc.alpha *
                 EstimateDirect(scene, this, arena, light, pc, nc, vc.wPrev,
                                vc.isect.rayEpsilon, time, vc.bsdf, rng,
                                ls.lightSample, ls.bsdfSample,
                                BxDFType(BSDF_ALL & ~BSDF_SPECULAR)) / lightPdf;
            PBRT_MLT_FINISHED_ESTIMATE_DIRECT();
        }
        previousSpecular = vc.specularBounce;
        allSpecular &= previousSpecular;
        L += Ld / (i + 1 - nSpecularVertices[i+1]);
        if (!vc.specularBounce) {
            // Loop over light path vertices and connect to camera vertex
            for (int j = 0; j < lightPathLength; ++j) {
                const PathVertex &vl = lightPath[j];
                const Point &pl = vl.bsdf->dgShading.p;
                const Normal &nl = vl.bsdf->dgShading.nn;
                if (!vl.specularBounce) {
                    // Compute contribution between camera and light vertices
                    Vector w = Normalize(pl - pc);
                    Spectrum fc = vc.bsdf->f(vc.wPrev, w) * (1 + vc.nSpecularComponents);
                    Spectrum fl = vl.bsdf->f(-w, vl.wPrev) * (1 + vl.nSpecularComponents);
                    if (fc.IsBlack() || fl.IsBlack()) continue;
                    Ray r(pc, pl - pc, 1e-3f, .999f, time);
                    if (!scene->IntersectP(r)) {
                        // Compute weight for bidirectional path, _pathWt_
                        float pathWt = 1.f / (i + j + 2 - nSpecularVertices[i+j+2]);
                        float G = AbsDot(nc, w) * AbsDot(nl, w) / DistanceSquared(pl, pc);
                        L += (vc.alpha * fc * G * fl * vl.alpha) * pathWt;
                    }
                }
            }
        }
    }
    // Add contribution of escaped ray, if any
    if (!eAlpha.IsBlack() && previousSpecular &&
        (directLighting == NULL || !allSpecular))
        for (uint32_t i = 0; i < scene->lights.size(); ++i)
           L += eAlpha * scene->lights[i]->Le(eRay);
    PBRT_MLT_FINISHED_LBIDIR();
    return L;
}
Beispiel #27
0
void read_n_tri_object(CHUNK *chunk)
{
	CHUNK
		*c,
		*c_point,
		*c_face,
		*c_tex;

	c = chunk->Child;
	do
	{
		if(POINT_ARRAY == c->hdr.id) c_point = c;
		else if(FACE_ARRAY == c->hdr.id) c_face = c;
		else if(TEX_VERTS == c->hdr.id) c_tex = c;

		c = c->Next;
	}
	while(c != chunk->Child);

	if(!c_point->data) return;
	WORD point_count = *(WORD*)c_point->data;
	_3DS_POINT *points = (_3DS_POINT*)((BYTE*)c_point->data + sizeof(WORD));

#if 1
	/************************************/
	for(int a = 0; a < point_count; a++)
	{
		//points[a].x *= 1.2f;
		points[a].y += 2.5f;
		//points[a].z *= 1.2f;
	}
	/************************************/
#endif

	if(!c_face->data) return;
	WORD face_count = *(WORD*)c_face->data;
	_3DS_FACE *faces = (_3DS_FACE*)((BYTE*)c_face->data + sizeof(WORD));

	WORD w = sizeof(_3DS_FACE) * face_count;

	_3DS_FACE *new_faces;
	new_faces = (_3DS_FACE*)malloc(w);
	memset(new_faces, 0, w);

	WORD i = 0, f;
	for(f = 0; f < face_count; f++)
	{
		D3DVECTOR vA = D3DVECTOR(points[faces[f].b].x, points[faces[f].b].y, points[faces[f].b].z) - D3DVECTOR(points[faces[f].a].x, points[faces[f].a].y, points[faces[f].a].z);
		D3DVECTOR vB = D3DVECTOR(points[faces[f].c].x, points[faces[f].c].y, points[faces[f].c].z) - D3DVECTOR(points[faces[f].a].x, points[faces[f].a].y, points[faces[f].a].z);
		D3DVECTOR n = Normalize(CrossProduct(Normalize(vA), Normalize(vB)));

		if((n.x <= 1.0f) && (n.x >= -1.0f) && (n.y <= 1.0f) && (n.y >= -1.0f) && (n.z <= 1.0f) && (n.z >= -1.0f))
		{
			new_faces[i].a = faces[f].a;
			new_faces[i].b = faces[f].b;
			new_faces[i].c = faces[f].c;
			new_faces[i].flag = faces[f].flag;
			i++;
		}
		else
			dwVertFixCount++;
	}

	free(c_face->data);
	c_face->data = 0;
	c_face->data_size = 0;

	w = sizeof(WORD) + sizeof(_3DS_FACE) * i;
	c_face->data = malloc(w);
	c_face->data_size = w;

	w -= sizeof(WORD);
	*(WORD*)c_face->data = i;
	memcpy((BYTE*)c_face->data + sizeof(WORD), new_faces, w);

	free(new_faces);

	if(c_face->Child)
	{
		CHUNK *chunk0 = c_face->Child;
		do
		{
			if(chunk0->data)
			{
				char sz[17];
				strcpy(sz, (char*)chunk0->data);

				free(chunk0->data);
				chunk0->data = 0;
				chunk0->data_size = 0;

				f = lstrlen(sz) + 1;
				chunk0->data_size = f + sizeof(WORD) + sizeof(WORD) * i;
				chunk0->data = malloc(chunk0->data_size);
				strcpy((char*)chunk0->data, sz);

				WORD *pw = (WORD*)((BYTE*)chunk0->data + f);
				*pw++ = i;

				for(f = 0; f < i; f++) *pw++ = f;
			}
			chunk0 = chunk0->Next;
		}
		while(chunk0 != c_face->Child);
	}
}
void main(int argc, char *argv[])
{

	FILE *fptr;
	char *inputHeader;
	int inputCols, inputRows, inputBytes;
	char Header_1[320];
	unsigned char *inputImage, *initialContour;
	int initCol[42], initRow[42];
	int index = 0;
	int contourSqrDist[42];
	double mean = 0;
	double variance[42];
	unsigned char *normalGrad, *normalGrad_x, *normalGrad_y;
	double *gradXImage, *gradYImage, *grad;
	int sumX, sumY;
	int r,c,r2,c2;
	double *energyImage;
	unsigned char *finalContour;
	int newPosition;
	double cellAverage[42];
	double *varianceImage, *distanceImage;
	double *normalVariance, *normalDistance, *normalSobel;

	printf("Initialization done!\n");
	
	if ((fptr=fopen("hawk.ppm","r"))==NULL)
	{
		printf("Unable to open input file for reading\n");
		exit(0);
	}
	

	if ((fptr=fopen("hawk_init.txt","r"))==NULL)
	{
		printf("Unable to open contour table for reading\n");
		exit(0);
	}

	printf("Input Check done!\n");


	//Open and load input image
	fptr = fopen("hawk.ppm", "r");
	fscanf(fptr,"%s %d %d %d",&inputHeader, &inputCols, &inputRows, &inputBytes);	
	Header_1[0]=fgetc(fptr);	/* read white-space character that separates header */
	inputImage = (unsigned char*)calloc(inputCols*inputRows,sizeof(unsigned char));
	fread(inputImage, 1, inputCols*inputRows, fptr);
	fclose(fptr);
	printf("Input file opened!\n");


	//Open and load initial contour points
	fptr = fopen("hawk_init.txt","r");
	while(fscanf(fptr,"%d %d\n", &initCol[index], &initRow[index]) != EOF)
	{
		index++;
	}
	fclose(fptr);
	for (int i = 0; i < 42; i++)
	{
		printf("%d. %d %d \n",i+1, initCol[i], initRow[i]);
	}
	printf("Initial contour points loaded!\n");


	//Copy input image into initialcontour
	initialContour = (unsigned char*)calloc(inputCols*inputRows, sizeof(unsigned char));
	for (int i = 0; i < inputCols*inputRows; i++)
	{
		initialContour[i] = inputImage[i];
	}


	//Draw plus at contour points
	for (int i = 0; i < 42; i++)
	{
		DrawPlus(initialContour, initCol[i], initRow[i], inputCols, 0);
	}
	//Write out initial contour image
	fptr=fopen("initial_contour.ppm","w");
	fprintf(fptr,"P5 %d %d 255\n",inputCols,inputRows);
	fwrite(initialContour,inputCols*inputRows,1,fptr);
	fclose(fptr);

	//Allocate memory to all images
	distanceImage = (double*)calloc(inputCols*inputRows, sizeof(double));
	gradXImage = (double*)calloc(inputCols*inputRows, sizeof(double));
	gradYImage = (double*)calloc(inputCols*inputRows, sizeof(double));
	grad = (double*)calloc(inputCols*inputRows, sizeof(double));
	energyImage = (double*)calloc(inputCols*inputRows, sizeof(double));
	finalContour = (unsigned char*)calloc(inputCols*inputRows, sizeof(unsigned char));
	normalGrad = (unsigned char*)calloc(inputCols*inputRows, sizeof(unsigned char));
	normalGrad_x = (unsigned char*)calloc(inputCols*inputRows, sizeof(unsigned char));
	normalGrad_y = (unsigned char*)calloc(inputCols*inputRows, sizeof(unsigned char));
	varianceImage = (double*)calloc(inputCols*inputRows, sizeof(double));
	normalVariance = (double*)calloc(inputCols*inputRows, sizeof(double));
	normalDistance = (double*)calloc(inputCols*inputRows, sizeof(double));
	normalSobel = (double*)calloc(inputCols*inputRows, sizeof(double));

	//Sobel filter kernels of order 3x3
	int sobelX[9] = {1, 0, -1, 2, 0, -2, 1, 0, -1};
	int sobelY[9] = {1, 2, 1, 0, 0, 0, -1, -2, -1};


	//Compute external energy term
	for (r = 0; r < inputRows; r++)
	{
		for (c = 0; c < inputCols; c++)
		{
			sumX = 0;
			sumY = 0;
			for (r2=-1; r2<=1; r2++)
				for (c2=-1; c2<=1; c2++)
				{	
					sumX += inputImage[(r+r2)*inputCols+(c+c2)]*sobelX[(r2+1)*3+c2+1];
					sumY += inputImage[(r+r2)*inputCols+(c+c2)]*sobelY[(r2+1)*3+c2+1];
				}
			gradXImage[(r*inputCols)+c]=sumX;
			gradYImage[(r*inputCols)+c]=sumY;
			grad[(r*inputCols)+c] = (SQUARE(sumX) + SQUARE(sumY));
		}
	}

	NormalizeGray(gradXImage, inputCols, inputRows, normalGrad_x, 255);
	NormalizeGray(gradYImage, inputCols, inputRows, normalGrad_y, 255);
	NormalizeGray(grad, inputCols, inputRows, normalGrad, 255);


	//Calculate Internal energies for 'n' iterations
	int iteration = 10;
	while(iteration>0)
	{

		for (int i = 0; i < 42; i++)
		{
			int next_col = (i+1)%42;
			int next_row = (i+1)%42;
			
			//Interal energy 1
			cellAverage[i] = CalculateCellDistance(distanceImage, initCol[i], initRow[i], initCol[next_col], initRow[next_row], inputCols);

			//Interal energy 2
			CalculateCellVariance(varianceImage, distanceImage, cellAverage[i], initCol[i], initRow[i], initCol[next_col], initRow[next_row], inputCols);

		}

		//Normalize the energies to 0-1 level
		for (int i = 0; i < 42; i++)
		{
			Normalize(varianceImage, inputCols, inputRows, initCol[i], initRow[i], normalVariance,1);
			Normalize(distanceImage, inputCols, inputRows, initCol[i], initRow[i], normalDistance,1);
			Normalize(grad, inputCols, inputRows, initCol[i], initRow[i], normalSobel,1);
		}

		for (int i = 0; i < inputCols*inputRows; i++)
		{
			energyImage[i] = (normalDistance[i] + normalVariance[i] - normalSobel[i])/3;
			finalContour[i] = inputImage[i];
		}

		
		//Move contour point to position of minimum energy 
		for (int i = 0; i < 42; i++)
		{

			int curRow = initRow[i];
			int curCol = initCol[i];

			int minEnergy = energyImage[curRow*inputCols+curCol];
			int newCol, newRow;

			for (int y = -3; y <=3; y++)
			{
				for (int x = -3; x <=3; x++)
				{
					if (energyImage[(curRow+y)*inputCols+curCol+x] < minEnergy)
					{
						newCol = curCol+x;
						newRow = curRow+y;
					}

				}
			}

			DrawPlus(finalContour, newCol, newRow, inputCols, 0);
			initRow[i] = newRow;
			initCol[i] = newCol; 

		}

		iteration--;
		printf("iterations = %d\n",iteration);
	}

	//Print final positions
	fptr=fopen("output.txt","w");
	for (int i = 0; i < 42; i++)
	{
		fprintf(fptr, "%d   %d\n", initCol[i], initRow[i]);
		printf("%d %d\n", initCol[i], initRow[i]);
	}
	fclose(fptr);

	//Write out the output images
	fptr=fopen("normalized_gradient_x.ppm","w");
	fprintf(fptr,"P5 %d %d 255\n",inputCols,inputRows);
	fwrite(normalGrad_x,inputCols*inputRows,1,fptr);
	fclose(fptr);

	fptr=fopen("normalized_gradient_y.ppm","w");
	fprintf(fptr,"P5 %d %d 255\n",inputCols,inputRows);
	fwrite(normalGrad_y,inputCols*inputRows,1,fptr);
	fclose(fptr);

	fptr=fopen("normalized_gradient.ppm","w");
	fprintf(fptr,"P5 %d %d 255\n",inputCols,inputRows);
	fwrite(normalGrad,inputCols*inputRows,1,fptr);
	fclose(fptr);

	fptr=fopen("final_contour.ppm","w");
	fprintf(fptr,"P5 %d %d 255\n",inputCols,inputRows);
	fwrite(finalContour,inputCols*inputRows,1,fptr);
	fclose(fptr);

	//Free allocated memory
	free(initialContour);
	free(distanceImage);
	free(gradXImage);
	free(gradYImage);
	free(grad);
	free(energyImage);
	free(finalContour); 
	free(normalGrad);
	free(normalGrad_x);
	free(normalGrad_y);
	free(varianceImage);
	free(normalVariance);
	free(normalDistance);
	free(normalSobel);
}
float Random_Floorplanning(Clo_Red_Graph &fp,int times, int& A, int& W){
  Solution Best;  
  Normalize(fp, A, W);
  fp.contour_packing();
  fp.compute_wire_length(); 
  fp.compute_cost(alpha, beta, A, W); 
  fp.get_solution(Best);
   
  double total_cost=0.0, pre_cost, cost;
  int t = 0;
  int N = times;
  pre_cost = fp.get_cost();
  do{
      for(int i=0; i < N; i++){
        fp.perturbate1();
        fp.contour_packing();
        fp.compute_wire_length();
        fp.compute_cost(alpha, beta, A, W);

        cost = fp.get_cost();
        //cout<<"cost="<<cost<<endl;
        if(cost-pre_cost > 0.0){
          total_cost+= (cost-pre_cost);
          t++;
          pre_cost = cost;
        }
       
        if(cost <= Best.Cost){
          fp.get_solution(Best);
          //if(alpha!=0.0&&beta!=0.0){
          //  cout << "cost="<< Best.Cost<<", < Area, Wire > = " <<  Best.Area <<
          //      ", " << Best.Wire <<" >" << endl;                           
          //}else{ 
          //  cout << "==> Cost=" << Best.Cost << endl;
          //}
        }

//        if((double(fp.getWireLength()/W))<1){
//           W=fp.getWireLength();
//           fp.compute_cost(alpha, beta, A, W);
//           pre_cost=fp.get_cost();
//           double best_cost=0.5*(((double)(Best.Area))/A+
//                                ((double)(Best.Wire))/W);
//           if(pre_cost < best_cost){
//              fp.get_solution(Best);
//              cout<<"Tuing Wire"<<endl;
//              cout<<"************************************"<<endl;
//              cout << "   ==> < Area, Wire > = " <<  Best.Area <<
//                ", " << Best.Wire <<" >" << endl;                                 
//              cout<<"&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&"<<endl;  
//           }
//        }
//      }

//      if(((double(fp.getArea()))/(double(A))<0.9)){
//         //cout<<"Tuning Area"<<endl;
//         A=fp.getArea();
//         fp.compute_cost(alpha, beta, A, W);
//         pre_cost=fp.get_cost();
//         double best_cost=0.5*(((double)(Best.Area))/A+
//                              ((double)(Best.Wire))/W);
//         if(pre_cost < best_cost){
//            fp.get_solution(Best);
           // cout<<"best cost="<<best_cost<<endl;
           // cout<<"************************************"<<endl;
           // cout << "   ==> < Area, Wire > = " <<  Best.Area <<
           //      ", " << Best.Wire <<" >" << endl;                                 
           // cout<<"&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&"<<endl;  
//         }
      }
  }while(total_cost==0.0);
  fp.recover(Best); 
  A=fp.getArea();
  W=fp.getWireLength();
//  W=Best.Area;
//  fp.compute_cost(alpha, beta, A, W);
  return (total_cost/t);
}
Beispiel #30
0
boolean FileBrowser::IsADirectory(const char* path) {
    return dir->IsADirectory(Normalize(path));
}