Пример #1
0
/*
** Create a file name, by concatenation
** returns TRUE if file exists FALSE otherwise
*/
Bool MakeFileName(char file[128], const char *path, const char *dir, const
    char *sdir, const char *name, const char *extens)
{  FILE *fp;
   char name2[8];  /* AYM 1999-01-13: keep checker happy */
   /* deal with VILE strange name
   ** replace the VILE[ VILE\ VILE]
   ** by          VIL@A VIL@B VIL@C
   */
   Normalise(name2,name);

   /* FIXME AYM 1999-06-09: Not sure whether it is a good thing
      to keep this translation scheme for the Unix version.
      However, removing it would make the DOS version and the
      Unix version incompatible. */
   switch(name2[4])
   { case '[':  name2[4]='$';break;
     case '\\': name2[4]='@';break;
     case ']':  name2[4]='#';break;
   }
   switch(name2[6])
   { case '[':  name2[6]='$';break;
     case '\\': name2[6]='@';break;
     case ']':  name2[6]='#';break;
   }

   NameDir(file,path,dir,sdir);
   /*
   ** file name
   */
   strcat(file,SEPARATOR);
   strncat(file,name2,8);
   strcat(file,".");
   strncat(file,extens,4);
   ToLowerCase(file);
   /*
   ** check if file exists
   */
   fp=fopen(file,FOPEN_RB);
   if(fp!=NULL)
   { fclose(fp);  /* AYM 1999-01-??: fclose() used to be called even if
		     fopen() had returned NULL! It gave beautiful segfaults. */
     return TRUE;
   }
   return FALSE;
}
Пример #2
0
void EigenVectors::FindEigenVector(DMatrix &egvts, double egvl, int ind) const {
    DArray egvt, darr;
    DMatrix dmat = input_, dmatprev;
    double det = 0.;
    int i1, i2, j1, size = egvts.size(), rs = size;
    InitArray(egvt, size);
    darr = egvt;
    for(i1 = 0; i1 < size; ++i1) {
        dmat[i1][i1] -= egvl;
    }
    for(i1 = 0; i1 < ind && det == 0.; ++i1) {
        for(j1 = 0; j1 < size; ++j1) {
            dmat[i1][j1] = egvts[j1][i1];
        }
        det = ComputeSystem(dmat, darr);
    }
    if(det == 0.) {
        egvt[ind] = 1.;
        dmatprev = dmat;
        rs = TrimSystem(dmat, darr);
        PopulateSystem(dmat, darr, dmatprev, ind);
        while(rs > 1) {
            det = ComputeSystem(dmat, darr);
            if(det != 0.) {
                break;
            }
            rs = TrimSystem(dmat, darr);
        }
        if(det == 0.) {
            darr[0] = (dmat[0][0] == 0.) ? 0. : (darr[0] / dmat[0][0]);
        }
        for(i1 = 0, i2 = 0; i2 < rs; ++i1) {
            if(i1 != ind) {
                egvt[i1] = darr[i2];
                ++i2;
            }
        }
    }
    if(rs < size) {
        Normalise(egvt);
    }
    for(i1 = 0; i1 < size; ++i1) {
        egvts[i1][ind] = RoundToZero(egvt[i1]);
    }
}
Пример #3
0
void GraphEditor::load(bool initgrid) 
// by default initgrid = true
// when editing (erasing edges, vertices,reorienting) initgrid = false
  {
  if(!is_init) //MAC
    {gwp->canvas->setSceneRect(0,0,contentsRect().width(),contentsRect().height());
    is_init=true;
    }
  //if(!is_init)return;
  clear();// delete all items
  if(gwp->pGG->nv() > staticData::MaxND)
      {Tprintf("Too big graph nv= %d (>%d)",gwp->pGG->nv(),staticData::MaxND);return;}
  GeometricGraph & G = *(gwp->pGG);

  if(initgrid)
      {Normalise();
      InitGrid(current_grid);
      }
  DrawGrid(current_grid);
  if(ShowGrid)showGrid(true);

  Prop<NodeItem *> nodeitem(G.Set(tvertex()),PROP_CANVAS_ITEM,(NodeItem *)NULL);
  Prop<EdgeItem *> edgeitem(G.Set(tedge()),PROP_CANVAS_ITEM,(EdgeItem *)NULL);
  nodeitem.SetName("nodeitem");edgeitem.SetName("edgeitem");

  for(tvertex v = 1;v <= G.nv();v++)
      nodeitem[v] =  CreateNodeItem(v,gwp);
  for(tedge e = 1;e <= G.ne();e++)
      edgeitem[e] = CreateEdgeItem(e,gwp); 

  if(staticData::ShowExtTbrin())
      {tedge e = G.extbrin().GetEdge();
      EdgeItem *edge = (G.extbrin() > 0) ? edgeitem[e]  : edgeitem[e]->opp;
      edge->SetColor(color[Green],false);
      } 

  Prop<bool> eoriented(G.Set(tedge()),PROP_ORIENTED,false);
  CreateColorItems(gwp,color_node,color_edge);
  G.vcolor.definit(color_node);
  G.vlabel.definit(0L);
  G.elabel.definit(0L);
  CreateThickItems(gwp,width_edge);
  G.ewidth.definit(width_edge);
  }
Пример #4
0
void FilePath::GetDir(FilePath* outDir) const
{
	Normalise();

	*outDir = FilePath();

	int len = static_cast<int>(m_storage.length());
	const char* chars = m_storage.c_str();
	for (int i = len - 1; i >= 0; --i)
	{
		if (chars[i] == '/')
		{
			chars += i + 1;
			*outDir = FilePath(chars);
			outDir->m_normalised = true;
			break;
		}
	}

}
Пример #5
0
bool FilePath::GetFilename(FilePath* outFilename) const
{
	Normalise();

	bool result = false;

	int len = static_cast<int>(m_storage.length());
	const char* chars = m_storage.c_str();
	for (int i = len - 1; i >= 0; --i)
	{
		if (chars[i] == '/')
		{
			chars += i + 1;
			*outFilename = FilePath(chars);
			outFilename->m_normalised = true;
			result = true;
			break;
		}
	}

	return result;
}
Пример #6
0
void FilePath::Join(const FilePath& rhs)
{
	Normalise();
	rhs.Normalise();

	size_t len = m_storage.length();
	bool trailingSlash = len > 0 && m_storage[len - 1] == '/';
	size_t rhsLen = rhs.m_storage.length();
	bool leadingSlash = rhsLen > 0 && rhs.m_storage[rhsLen - 1] == '/';

	//Copy only one slash if both leading and trailing
	if (leadingSlash && trailingSlash)
	{
		char buf[MB_MAX_PATH];
		memcpy(buf, m_storage.c_str(), len - 1);
		memcpy(buf + len, rhs.m_storage.c_str(), rhsLen);
	}
	//Join together without adding new slash
	else if (leadingSlash || trailingSlash)
	{
		m_storage += rhs.m_storage;
	}
	else
	{
		//No slash needed if our length is 0
		if (len == 0)
		{
			m_storage = rhs.m_storage;
		}
		else
		{
			//Add new slash
			char buf[MB_MAX_PATH];
			sprintf(buf, "%s/%s", m_storage.c_str(), rhs.m_storage.c_str());
			m_storage = buf;
		}
	}
}
Пример #7
0
/*
 Rotate a point p by angle theta around an arbitrary normal r
 Return the rotated point.
 Positive angles are anticlockwise looking down the axis towards the origin.
 Assume right hand coordinate system.
 */
XYZ ArbitraryRotate(XYZ p,double theta,XYZ r)
{
    XYZ q = {0.0,0.0,0.0};
    double costheta,sintheta;

    Normalise(&r);
    costheta = cos(theta);
    sintheta = sin(theta);

    q.x += (costheta + (1 - costheta) * r.x * r.x) * p.x;
    q.x += ((1 - costheta) * r.x * r.y - r.z * sintheta) * p.y;
    q.x += ((1 - costheta) * r.x * r.z + r.y * sintheta) * p.z;

    q.y += ((1 - costheta) * r.x * r.y + r.z * sintheta) * p.x;
    q.y += (costheta + (1 - costheta) * r.y * r.y) * p.y;
    q.y += ((1 - costheta) * r.y * r.z - r.x * sintheta) * p.z;

    q.z += ((1 - costheta) * r.x * r.z - r.y * sintheta) * p.x;
    q.z += ((1 - costheta) * r.y * r.z + r.x * sintheta) * p.y;
    q.z += (costheta + (1 - costheta) * r.z * r.z) * p.z;

    return(q);
}
Пример #8
0
/* read Blocks of the form
** [BLOCKID]
** identifier   ... anything ...
** identifier   ... anything ...
*/
static bool TXTfindSection(struct TXTFILE *TXT, bool Match)
{
    int16_t c = 0, val = 0, n;
    char buffer[8];
    while (1) {
        if (!TXTskipComment(TXT))
            return false;
        if (!TXTgetc(TXT, &c, &val))
            return false;
        if (c == '[') {
            for (n = 0; n < 256; n++) {
                if (!TXTgetc(TXT, &c, &val))
                    return false;
                if (c == ']') {
                    if (n < 8)
                        buffer[n] = '\0';
                    if (!Match)
                        return true;    /*any section is ok */
                    Normalise(buffer, buffer);  /*the right section? */
                    if (strncmp(buffer, TXT->Section, 8) == 0)
                        return true;
                    break;      /*not the right section */
                }
                if (!(val & (NAME | NUMBER)))
                    break;      /*not a section */
                if (n < 8)
                    buffer[n] = c;
            }
        }
        while (1) {             /*look for end of line */
            if (!TXTgetc(TXT, &c, &val))
                return false;
            if (val & NEWLINE)
                break;
        }
    }
}
void Player::Update(float dt)
{
	if(path.empty())
		return;

	if(next == NULL)
		next = path.back();

	float xDir = next->x - x, yDir = next->y - y;
	Normalise(xDir, yDir);

	rotation = DirToRot(xDir, yDir);

	x += xDir * dt * 400;
	y += yDir * dt * 400;

	if(Distance(x, y, next->x, next->y) < 3)
	{
		path.pop_back();
		if(path.size() > 0)
			nodeMap->ChangeLinkColor(next, path.back(), 255, 0, 0);
		next = NULL;
	}
}
Пример #10
0
void EventLoop(CCam & Camera1)
{
 bool quitit=false;
 SDL_Event event;
 SDL_MouseMotionEvent event2;
 SDL_keysym  *whatkey;
 bool mousedown=false;

int n_nodes;
bool old1,old2,old3;
bool case0, case1, case2, case3, case4, case5, case6, case7;

//  Go to while(!quitit) to see what happens once data set up

// Go to Render Scene for graphics bit
//


    bool exitnow=false;

    extern double X,Y,Z;
    X=-1e32;Y=-1e-32;Z=-1e32;
    xmax=X; ymax=Y, zmax=Z;
    xmin=-X; ymin=-Y, zmin=-Z;

    double xunit,yunit,zunit;
    xunit=1.0;yunit=1.0;zunit=1.0;

    // (On ,my machine) very slow  ndiv>9, pages memory
    // On Earth, ndiv=6 is the last stage where unsigned shorts
    // could be used for triangle and node numbers, and the length scale is ~200km.
    int ndiv=4;

    int Ttotal,Ntotal;

    Ttotal=8*(int)(pow(4,ndiv+1)-1)/3; 
    Ntotal=4*(int)(pow(4,ndiv)-1)+6;  

    int trinumbers[ndiv+1];
    int nodenumbers[ndiv+1];

    cout << "There will be " << endl;
    cout <<  Ttotal << "  Triangles in total " << endl;
    cout << 3*pow(4,ndiv)  << "  new nodes  in last subdivision " << endl;
    cout <<  Ntotal << " Nodes  in total "  << endl;

    trinumbers[0]=8;   //initial octahedron
    nodenumbers[0]=6;

    int trinum=8;


    Triangles=(Triangle*) calloc( Ttotal ,sizeof(Triangle));
    NodeV=(D3Dvec*)calloc( Ntotal, sizeof(D3Dvec));

    for(int i=0; i<Ntotal; i++){
	    NodeV[i]=D3Dvec(); } //initialise or bust!
    for(int i=0; i<Ttotal; i++){
	    Triangles[i]=Triangle(); } //initialise


    cout << " Starting Subdivision " << endl;


 //   if_stream opens for input
 //   of_stream opens for output
 //   f_stream opens for both
 //
    double x,y,z;
 // position vectors for basic octahedron 
    x=0.0; y=-1.0; z=0.0;
    NodeV[0].SetVec(x,y,z);
    x=1.0; y=0.0; z=0.0;
    NodeV[1].SetVec(x,y,z);
    x=0.0; y=1.0; z=0.0;
    NodeV[2].SetVec(x,y,z);
    x=-1.0; y=0.0; z=0.0;
    NodeV[3].SetVec(x,y,z);
    x=0.0; y=0.0; z=1.0;
    NodeV[4].SetVec(x,y,z);
    x=0.0; y=0.0; z=-1.0;
    NodeV[5].SetVec(x,y,z);

    int in,jn,kn;
    char quad, otherquad;

 //node numbers for basic octahedron
    quad=1;
    in=1-1;jn=2-1;kn=5-1;
    Triangles[0].SetTri(in, jn, kn);
    Triangles[0].SetQuad(quad);
    quad=2;
    in=2-1;jn=3-1;kn=5-1;
    Triangles[1].SetTri(in, jn, kn);
    Triangles[1].SetQuad(quad);
    quad=3;
    in=3-1;jn=4-1;kn=5-1;
    Triangles[2].SetTri(in, jn, kn);
    Triangles[2].SetQuad(quad);
    quad=4;
    in=4-1;jn=1-1;kn=5-1;
    Triangles[3].SetTri(in, jn, kn);
    Triangles[3].SetQuad(quad);

    quad=1;
    in=2-1;jn=1-1;kn=6-1;
    Triangles[4].SetTri(in, jn, kn);
    Triangles[4].SetQuad(quad);
    quad=2;
    in=3-1;jn=2-1;kn=6-1;
    Triangles[5].SetTri(in, jn, kn);
    Triangles[5].SetQuad(quad);
    quad=3;
    in=4-1;jn=3-1;kn=6-1;
    Triangles[6].SetTri(in, jn, kn);
    Triangles[6].SetQuad(quad);
    quad=4;
    in=1-1;jn=4-1;kn=6-1;
    Triangles[7].SetTri(in, jn, kn);
    Triangles[7].SetQuad(quad);





    //Neighbours for each edge of each triangle
    //Triangle edges in triangle are the edge number
    //of the edge in the NEIGHBOUR
    //
    //For instance Edge 1 of first triangle
    //is edge 1 of triangle 5, but in opposite direction
    in=5-1;jn=4-1;kn=2-1;
    Triangles[0].SetNeighb(in, jn, kn);

    in=6-1;jn=1-1;kn=3-1;
    Triangles[1].SetNeighb(in, jn, kn);

    in=7-1;jn=2-1;kn=4-1;
    Triangles[2].SetNeighb(in, jn, kn);

    in=8-1;jn=3-1;kn=1-1;
    Triangles[3].SetNeighb(in, jn, kn);

    // *********************************************

    in=1-1;jn=6-1;kn=8-1;
    Triangles[4].SetNeighb(in, jn, kn);

    in=2-1;jn=7-1;kn=5-1;
    Triangles[5].SetNeighb(in, jn, kn);

    in=3-1;jn=8-1;kn=6-1;
    Triangles[6].SetNeighb(in, jn, kn);

    in=4-1;jn=5-1;kn=7-1;
    Triangles[7].SetNeighb(in, jn, kn);

    ntri=8; n_nodes=6; ntrinew=0;   //we have 8 triangles and 6 nodes

    n_nodes=n_nodes-1;  // 6 nodes 0-5

    int *pSplit0,*pSplit1,*pSplit2,*pSplit3;
    bool split_this;

    int in1,in2,in3;
    int is1,is2;
    int nn1,nn2,nn3;

    int inode1,inode2,inode3;
    int new0,new1,new2,new3;  //serves for new node or triangle numbers
    int new1N,new2N,new3N;  

    istart=0;
    istop=8;

      // split all triangles at this level if the neighbours 
      // are on the same level. Then every split triangle
      // has an unsplit neighbour and vice versa
      //
	    //recursive subdivision
	    //
	    for(int idiv=0; idiv <ndiv; idiv++){
		 ntrinew=0;
		 nnodenew=0;
	    for(int itri=istart;itri<istop;itri++){
		    if( Triangles[itri].GetN() ){
		    in1=Triangles[itri].GetN1();
		    in2=Triangles[itri].GetN2();
		    in3=Triangles[itri].GetN3();
		    }
		    else { cout <<" No Neighbours " << endl;  exit(0);  }

		    pSplit0=Triangles[itri].GetS();
		    pSplit1=Triangles[in1].GetS();
		    pSplit2=Triangles[in2].GetS();
		    pSplit3=Triangles[in3].GetS();

                    if(!pSplit0){split_this=true;} else {split_this=false;}

		    if(split_this){

		    // Split This Triangle into 4 with three new nodes

		    bool NodeExists1=false;
		    bool NodeExists2=false;
		    bool NodeExists3=false;

		    if(pSplit3)NodeExists1=true;
		    if(pSplit2)NodeExists2=true;
		    if(pSplit1)NodeExists3=true;

		    int oldnode1=-1,oldnode2=-1,oldnode3=-1;

                    old1=false; old2=false; old3=false;
		    // nodes of internal triangle to current replacement
		    // in current leve;
		    if(NodeExists1){
			    // split exists on edge 3 of current T
			    quad=Triangles[itri].GetQuad();
			    otherquad=Triangles[in3].GetQuad();
                           if(quad != otherquad){
			    oldnode1=
			    Triangles[Triangles[in3].GetS2()].Get3();}
			   else {
			    oldnode1=
			    Triangles[Triangles[in3].GetS3()].Get3();}
			    old1=true;
		    }
		    if(NodeExists2){
			    // split exists on edge 2 of current T
			    //
			    quad=Triangles[itri].GetQuad();
			    otherquad=Triangles[in2].GetQuad();
			    if(quad != otherquad){
			    oldnode2=
			    Triangles[Triangles[in2].GetS3()].Get3(); }
			    else  {
			    oldnode2=
			    Triangles[Triangles[in2].GetS2()].Get3(); }

			    old2=true;
		    }
		    if(NodeExists3){
			    //  edge 1 always matches edge1
			    oldnode3=
			    Triangles[Triangles[in1].GetS2()].Get2();
			    old3=true;
		    }

		    if(oldnode1 < 0){
		       n_nodes++;
		       nnodenew++;
		       NodeV[n_nodes].SetX( 
				NodeV[ Triangles[itri].Get2() ].GetX()
			       +(
				NodeV[ Triangles[itri].Get3() ].GetX()
				-NodeV[ Triangles[itri].Get2() ].GetX()
				)/2.0
				);

		       NodeV[n_nodes].SetY( 
				NodeV[ Triangles[itri].Get2() ].GetY()
			       +(
				NodeV[ Triangles[itri].Get3() ].GetY()
				-NodeV[ Triangles[itri].Get2() ].GetY()
				)/2.0
				);
		       NodeV[n_nodes].SetZ( 
				NodeV[ Triangles[itri].Get2() ].GetZ()
			       +(
				NodeV[ Triangles[itri].Get3() ].GetZ()
				-NodeV[ Triangles[itri].Get2() ].GetZ()
				)/2.0
				);
		   //   Normalise(NodeV[n_nodes]);
		    }


		    if(oldnode2 < 0){
		       n_nodes++;
		       nnodenew++;
		       NodeV[n_nodes].SetX( 
				NodeV[ Triangles[itri].Get1() ].GetX()
			       +(
				NodeV[ Triangles[itri].Get3() ].GetX()
				-NodeV[ Triangles[itri].Get1() ].GetX()
				)/2.0
				);
		       NodeV[n_nodes].SetY( 
				NodeV[ Triangles[itri].Get1() ].GetY()
			       +(
				NodeV[ Triangles[itri].Get3() ].GetY()
				-NodeV[ Triangles[itri].Get1() ].GetY()
				)/2.0
				);
		       NodeV[n_nodes].SetZ( 
				NodeV[ Triangles[itri].Get1() ].GetZ()
			       +(
				NodeV[ Triangles[itri].Get3() ].GetZ()
				-NodeV[ Triangles[itri].Get1() ].GetZ()
				)/2.0
				);
		   //   Normalise(NodeV[n_nodes]);
		    }
                    if(oldnode3 < 0){
		       n_nodes++;
		       nnodenew++;
		       NodeV[n_nodes].SetX( 
				NodeV[ Triangles[itri].Get1() ].GetX()
			       +(
				NodeV[ Triangles[itri].Get2() ].GetX()
				-NodeV[ Triangles[itri].Get1() ].GetX()
				)/2.0
				);
		       NodeV[n_nodes].SetY( 
				NodeV[ Triangles[itri].Get1() ].GetY()
			       +(
				NodeV[ Triangles[itri].Get2() ].GetY()
				-NodeV[ Triangles[itri].Get1() ].GetY()
				)/2.0
				);
		       NodeV[n_nodes].SetZ( 
				NodeV[ Triangles[itri].Get1() ].GetZ()
			       +(
				NodeV[ Triangles[itri].Get2() ].GetZ()
				-NodeV[ Triangles[itri].Get1() ].GetZ()
				)/2.0
				);
		    //  Normalise(NodeV[n_nodes]);
	    }

		     isplit=istop+ntrinew;

		     new0=isplit;
		     new1=isplit+1;
		     new2=isplit+2;
		     new3=isplit+3;
	    
		     Triangles[itri].SetSplit( new0, new1, new2, new3);


		       if(old1)inode1=oldnode1;
		       if(old2)inode2=oldnode2;
		       if(old3)inode3=oldnode3;
                       case0=false;
                       case1=false;
                       case2=false;
                       case3=false;
                       case4=false;
                       case5=false;
                       case6=false;
                       case7=false;

		       if( !old1 && !old2 && !old3)case0=true; 
		       if( old1 && old2 && old3)case7=true;

		       if(case0 ){
			       inode1=n_nodes-2;
			       inode2=n_nodes-1;
			       inode3=n_nodes-0;
		       }
		       if(case7){
			       inode1=oldnode1;
			       inode2=oldnode2;
			       inode3=oldnode3;
		       }


		       if(!case0 &&  !case7)
		       {
		       if(old1){
			       if(old2 || old3){
			       if(old2){   
				  case4=true;   // nodes 1 and 2 exist 
				  inode1=oldnode1;
				  inode2=oldnode2;
				  inode3=n_nodes-0;
			          }
				  else
				  {
			           case6=true;    // nodes 1 and 3 exist
			           inode1=oldnode1;
			           inode2=n_nodes-0;
			           inode3=oldnode3;
				  }
			       }
				      else 
				      {
					      case1=true;  //only node 1 exists
				              inode1=oldnode1;
				              inode2=n_nodes-1;
				              inode3=n_nodes-0;  
				      }
			         }//endif old1
		       if(old2){
			       if(!old1){   // case 4 done above
			       if(old3){   
				  case5=true;   //nodes 2 and 3 exist
				  inode1=n_nodes-0;
				  inode2=oldnode2;
				  inode3=oldnode3;
			          }
				  else
				  {
				  case2=true;  //only node 2 exists
				  inode1=n_nodes-1;
				  inode2=oldnode2;
				  inode3=n_nodes-0;
				  }
			       }
		       } //endif old2
		       if(old3){
			       if( !old1 && !old2){
			       //  1 and 3 and 2 and 3 done already
			          case3=true; 
				  inode1=n_nodes-1;
				  inode2=n_nodes-0;
				  inode3=oldnode3;
			       }
		       }
		       }  //endif (NOT case 0) AND (NOT case 7)

		       quad=Triangles[itri].GetQuad();
		       Triangles[new0].SetTri(inode1, inode2, inode3);  //Centre T
		       Triangles[new0].SetQuad(quad);

		      Triangles[new1].SetTri(Triangles[itri].Get1(), inode3, inode2); 
		      Triangles[new1].SetQuad(quad);
		      Triangles[new2].SetTri(inode3, Triangles[itri].Get2(), inode1);
		      Triangles[new2].SetQuad(quad);
		      Triangles[new3].SetTri(inode2, inode1, Triangles[itri].Get3());
		      Triangles[new3].SetQuad(quad);

		 
                      //Set Neighbours for centre Triangle;
		       new1N=new3;
		       new2N=new2;
		       new3N=new1;
		       Triangles[new0].SetNeighb(new1N,new2N,new3N);
		       Triangles[new1].SetN3(new0);
		       Triangles[new2].SetN2(new0);
		       Triangles[new3].SetN1(new0);

                       if(pSplit1){
			      // have split neighbours on edge 1
			      // These are
			      is1=Triangles[in1].GetS3();
			      is2=Triangles[in1].GetS2();

			      Triangles[new1].SetN1(is1);
			      Triangles[new2].SetN1(is2);
                               
			      Triangles[is1].SetN1(new1); 
			      Triangles[is2].SetN1(new2); 
			      //independent of quadrant
		       }
                       if(pSplit2){
			      // have split neighbours on edge 2
			      // These are
			      quad=Triangles[itri].GetQuad();
			      otherquad=Triangles[in2].GetQuad();

			      if(quad != otherquad){
			      is1=Triangles[in2].GetS3();
			      is2=Triangles[in2].GetS4();
			      }
			      else {
			      is1=Triangles[in2].GetS4();
			      is2=Triangles[in2].GetS2();
			      }
			      if(quad != otherquad){
			      Triangles[is1].SetN3(new1); 
			      Triangles[is2].SetN3(new3);
			      }
			      else {
			      Triangles[is1].SetN2(new1);
			      Triangles[is2].SetN2(new3);
			      }
			      Triangles[new1].SetN2(is1);
			      Triangles[new3].SetN2(is2);

		       }
                       if(pSplit3){
			      // have split neighbours on edge 3
			      // These are
			      quad=Triangles[itri].GetQuad();
			      otherquad=Triangles[in3].GetQuad();
                              if(quad != otherquad){
			      is1=Triangles[in3].GetS2();
			      is2=Triangles[in3].GetS4(); 
			      }
				      else {
			      is1=Triangles[in3].GetS4();
			      is2=Triangles[in3].GetS3(); 
				      }
                              if(quad != otherquad){
			      Triangles[is1].SetN2(new2);
			      Triangles[is2].SetN2(new3);
			      }
			      else
			      {
			      Triangles[is1].SetN3(new2);
			      Triangles[is2].SetN3(new3);  
			      }

			      Triangles[new2].SetN3(is1);
			      Triangles[new3].SetN3(is2);
		       }
		       
		       
		     ntrinew=ntrinew+4;

		    }  //endif neighbours unsplit
	    }  //end loop over tranche of triangles
	      istart=istop;
	      istop=istop+ntrinew;
	   //   cout << " new istart=" << istart  << endl;
	   //   cout << "new istop=" << istop << endl;

	      trinumbers[idiv+1]=ntrinew;
	      nodenumbers[idiv+1]=n_nodes;

	      trinum=trinum+ntrinew;
	      cout << " There are " << ntrinew << " new Triangles in this subdivision"<<endl;
	      cout << " There are " << trinum  << " Triangles in total "<<endl;
	      cout << " There are " << nnodenew << " new nodes in this subdivision "<< endl;
	      cout << " There are " << n_nodes+1 << " Nodes in total "<<endl;
	      cout << "idiv=" << idiv << endl;


	      int ie1, ie2, ie3,  ie4;
	      //check connections!
	      cout << "ISTART  ISTOP " << istart  << "  " << istop << endl;


	      for(int i=0; i< n_nodes; i++)
                Normalise(NodeV[i]);
				      }  


               // only cehck if we suspect something wrong!

/*
	      for(int itri=istart; itri < istop; itri++){

	//	  cout << "Checking T" << itri << endl;

                  in1=Triangles[itri].GetN1();
		  in2=Triangles[itri].GetN2();
		  in3=Triangles[itri].GetN3();

		  ie1=Triangles[itri].Get1();  //across edge 1
		  ie2=Triangles[itri].Get2();

		  ie3=Triangles[in1].Get1();  // Allways Opposite
		  ie4=Triangles[in1].Get2();

		  if( ie1 != ie4)cout << " edge mismatch  1   "
		  << "Ts " <<  itri  << " " << in1  << " " << ie1 << " " << ie2
		  << " in " << itri <<  "  and " << ie3 << " " << ie4 << endl;

		  ie1=Triangles[itri].Get1(); //  across edge 2
		  ie2=Triangles[itri].Get3();

		  quad=Triangles[itri].GetQuad();
		  otherquad=Triangles[in2].GetQuad();

		  if(quad != otherquad){
		  ie3=Triangles[in2].Get3();
		  ie4=Triangles[in2].Get2();}  // Same directions
		  else {
		  ie3=Triangles[in2].Get1();
		  ie4=Triangles[in2].Get3();    //Opposite directions
		  }

		  if( ie1 != ie4)cout << " edge mismatch  2   "
		  << "Ts " <<  itri  << " " << in1  << " " << ie1 << " " << ie2
		  << " in " << itri <<  "  and " << ie3 << " " << ie4 
	         << "  " << in2 << 
		 "  quads are " << (int)quad << " " << (int)otherquad <<endl;



		  ie1=Triangles[itri].Get2();  //across edge 3
		  ie2=Triangles[itri].Get3();

		  quad=Triangles[itri].GetQuad();
		  otherquad=Triangles[in3].GetQuad();

		  if(quad != otherquad){
		  ie3=Triangles[in3].Get3();     // Same directions
		  ie4=Triangles[in3].Get1(); }
		  else {
		  ie3=Triangles[in3].Get2();
		  ie4=Triangles[in3].Get3();    //  Opposite directions
		  }

		  if( ie1 != ie4)cout << " edge mismatch  3   "
		  << "Ts " <<  itri  << " " << in1  << " " << ie1 << " " << ie2
		  << " in " << itri <<  "  and " << ie3 << " " << ie4 
	         << "  " << in2 << 
		 "  quads are " << (int)quad << " " << (int)otherquad <<endl;
	      } */

	/*      for(int i=0; i<idiv+1; i++){
		      cout << " Node Numbers and Tri Numbers" << endl;
		      cout << nodenumbers[i] << "  " << trinumbers[i] << endl;
	      } */
	      /*
    cout << " nodes and triangles " << n_nodes << " " << trinum << endl;
    cout << 4*(pow(4,ndiv)-1)+6  << " nodes  in total " << n_nodes << endl;
    cout <<  ntrinew << "  new Triangles in last division" << endl;
    cout <<  Ttotal << "  Total number of triangles at all levels" << endl;

    }
    */
    cout << " calculate metric" << endl;

    double **Gmetric;
    Gmetric =(double**)calloc(   Ttotal, sizeof( double[3] )  );
    if(!Gmetric){ cout << "Memory Failed for Gmetric " << endl; exit(0);}


  //  double Gmetric[Ttotal][3];
    D3Dvec Va1,Vb1,VOrig;
    D3Dvec Va2,Vb2;  //used later but declare and initialise here

    Va1=D3Dvec();
    Vb1=D3Dvec();

    Va2=D3Dvec();
    Vb2=D3Dvec();

    VOrig=D3Dvec();
    double ex,why,zed;

    int i1,i2,i3;

    double rad=-1;

    for(int i=Ttotal-ntrinew; i<Ttotal; i++){
    Gmetric[i]=new double[3];
    i1=Triangles[i].Get1();
    i2=Triangles[i].Get2();
    i3=Triangles[i].Get3();
    x=NodeV[i1].GetX();
    y=NodeV[i1].GetY();
    z=NodeV[i1].GetZ();
    VOrig.SetVec(x,y,z);
    x=NodeV[i2].GetX()-VOrig.GetX();
    y=NodeV[i2].GetY()-VOrig.GetY();
    z=NodeV[i2].GetZ()-VOrig.GetZ();
    Va1.SetVec(x,y,z);
    x=NodeV[i3].GetX()-VOrig.GetX();
    y=NodeV[i3].GetY()-VOrig.GetY();
    z=NodeV[i3].GetZ()-VOrig.GetZ();
    Vb1.SetVec(x,y,z);
    Gmetric[i][0]=Va1.Dot(Va1);
    Gmetric[i][1]=Va1.Dot(Vb1);
    Gmetric[i][2]=Va1.Dot(Vb1);
     rad=Gmetric[i][0];
     rad=sqrt(rad)*6370.;
    }  


    // NodeV[0], NodeV[1], ....  NodeV[n_nodes] is n_nodes+1 nodes
    n_nodes=n_nodes+1;
   
    cout << "There were " << ntrinew << "  new triangles in last subdivision" << endl;

    cout << "There should be " << endl;
    cout <<  Ttotal << "  Triangles in total, there are " << istop << endl;
    cout << 3*(int)pow(4,ndiv)  << "  new nodes  in last subdivision " << endl;
    cout <<  Ntotal << " Nodes  in total, there are " << n_nodes << endl;

    cout << ntrinew
	   << "   triangles, length scales of order " <<  rad << " km for Earth" << endl;
    cout << "They are Triangles T[" << Ttotal-ntrinew  <<"] " <<
     "  to Triangles T[" << Ttotal <<"] " << endl;


    // Now for a geodesic !
    //
    // In this specific example we expect ndiv=4
    if(ndiv==4){
    int Tlow=680;    //triangle number range for ndiv=4
    int Thigh=2728;
    int Tstart0=1222;
    int Tstart, NextT;
    double xO,yO,zO;
    double x1,y1,z1;
    double x2,y2,z2;
    char qStart,qNext;
    double  d1, d2, lambda;
    double ds_total, ds_squared;
    bool escape;
    double alpha_exit, beta_exit;
    double alpha_start, beta_start;

    double alphaTstart, betaTstart; 
    // values of lambda to hit the line alpha=0, beta=0, alpha+beta=1.
    double Tol1=0.000001;
    // if fabs(d) less than this it lands on edge miles away or never at all
    double Tol2=1e-8;  //possibility that we land on a corner

    double alpha_e1, beta_e1;
    double alpha_e2, beta_e2;
    double alpha_e3, beta_e3;
    bool land_e1, land_e2, land_e3;
    double lambda_edge1, lambda_edge2, lambda_edge3;

    int Node1, Node2, Node3;

    Tstart=Tstart0;

    Node1=Triangles[Tstart].Get1();
    Node2=Triangles[Tstart].Get2();
    Node3=Triangles[Tstart].Get2();
    D3Dvec Rnode1,Rnode2,Rnode3;
    Rnode1=D3Dvec(); Rnode2=D3Dvec(); Rnode3=D3Dvec();

    xO=NodeV[Node1].GetX();
    yO=NodeV[Node1].GetY();
    zO=NodeV[Node1].GetZ();
    VOrig.SetVec(xO,yO,zO);

    x1=NodeV[Node2].GetX();
    y1=NodeV[Node2].GetY();
    z1=NodeV[Node2].GetZ();
    Rnode1.SetVec(x1,y1,z1);

    x2=NodeV[Node3].GetX();
    y2=NodeV[Node3].GetY();
    z2=NodeV[Node3].GetZ();
    Rnode2.SetVec(x2,y2,z2);

    Va1=Rnode2-Rnode1;
    Vb1=Rnode3-Rnode1;

    alpha_start=0.25, beta_start=0.25;
    d1=.5; d2=0.25;  

    land_e1=false; land_e2=false; land_e3=false;

    //alpha_start + d1 lambda=0 lands on edge2;
    //beta_start+ d2 lambda=0 lands on edge1;
     if( fabs(d1) > Tol1){lambda_edge1=-beta_start/d2; land_e1=true;}
     if( fabs(d2) > Tol1){lambda_edge2=-alpha_start/d1; land_e2=true;}
     if( fabs(d2+d2) > Tol1)
     {lambda_edge3=(1.0-alpha_start-beta_start)/(d1+d2); 
	     land_e3=true;}

     cout << "d1=" << d1 << endl;
     cout << "d2=" << d2 << endl;
     cout << "alpha_s=" << alpha_start << endl;
     cout << "beta_s=" << beta_start << endl;

     alpha_e1=alpha_start+lambda_edge1*d1;
     beta_e1=beta_start+lambda_edge1*d2;
     alpha_e2=alpha_start+lambda_edge2*d1;
     beta_e2=beta_start+lambda_edge2*d2;
     alpha_e3=alpha_start+lambda_edge3*d1;
     beta_e3=beta_start+lambda_edge3*d2;

     if(  (fabs(alpha_e1) < Tol2)  && (fabs(beta_e1) <Tol2) ){
		     // set it safely on edge 1
		     alpha_e1=2.*Tol2;
		     beta_e1=0.0;
		     }
     if(  (fabs(1.0-alpha_e1) < Tol2)  && (fabs(beta_e1) <Tol2) ){
		     // set it safely on edge 1
		     alpha_e1=1.0-2.0*Tol2;
		     beta_e1=0.0;
		     }

     if(  (fabs(alpha_e2) < Tol2)  && (fabs(beta_e2) <Tol2) ){
		     // set it safely on edge 2
		     alpha_e2=0.0;
		     beta_e2=2.0*Tol2;
		     }
     if(  (fabs(1.0-beta_e2) < Tol2)  && (fabs(alpha_e2) <Tol2) ){
		     // set it safely on edge 2
		     alpha_e2=0.0;
		     beta_e2=1.0-2.0*Tol2;
		     }

     if(  (fabs(1.0-alpha_e3-beta_e3) < Tol2)  ){
         if(fabs(alpha_e3) < Tol2){
		 // set it safely on edge 3
		 alpha_e3=2.0*Tol2;
		 beta_e3=1.0-alpha_e3;
	 }
         if(fabs(beta_e3) < Tol2){
		 // set it safely on edge 3
		 beta_e3=2.0*Tol2;
		 alpha_e3=1.0-beta_e3;
	 }
     }

   
/*     cout << "e1 " << alpha_e1 << "  L e1=" << lambda_edge1 << endl;
     cout << "e2 " << beta_e2 <<  "  L_e2=" <<  lambda_edge2 << endl;
     cout << "a e3 " << alpha_e3 << "  L_e3=" << lambda_edge3 << endl;
     cout << "b e3 " << beta_e3 << endl;  */

     if(lambda_edge1 <0.0 || alpha_e1 < 0.0 || alpha_e1 > 1.0)land_e1=false;
     if(lambda_edge2 <0.0 || beta_e2 < 0.0 || beta_e2 > 1.0)land_e2=false;

     if(lambda_edge3 <0.0 || alpha_e3 < 0.0 || alpha_e3 > 1.0)land_e3=false;
     if(lambda_edge3 <0.0 || beta_e3 < 0.0 || beta_e3 > 1.0)land_e3=false;

     cout << land_e1 << land_e2 << land_e3 << endl;

     escape=false;
     if(land_e1){
	     //beta_e1=0
	     ds_squared=
	     Gmetric[Tstart][0]*(alpha_e1-alpha_start)*(alpha_e1-alpha_start)
	     -2.0*Gmetric[Tstart][1]*(alpha_e1-alpha_start)*beta_start
	     +Gmetric[Tstart][2]*beta_start*beta_start;

	     ds_total=ds_total+sqrt(ds_squared);
	     escape=true;
	     alpha_exit=alpha_e1;
	     beta_exit=0.0;
     }
     if(land_e2){
	     //alpha_e1=0
	     ds_squared=
	     Gmetric[Tstart][0]*alpha_start*alpha_start
	     -2.0*Gmetric[Tstart][1]*alpha_start*(beta_e2-beta_start)
	     +Gmetric[Tstart][2]*(beta_e2-beta_start)*(beta_e2-beta_start);

	     ds_total=ds_total+sqrt(ds_squared);
	     escape=true;
	     beta_exit=beta_e2;
	     alpha_exit=0;
     }
     if(land_e3){
	     ds_squared=
	     Gmetric[Tstart][0]*(alpha_e3-alpha_start)*(alpha_e3-alpha_start)
	     +2.0*Gmetric[Tstart][1]*(alpha_e3-alpha_start)*(beta_e3-beta_start)
	     +Gmetric[Tstart][2]*(beta_e3-beta_start)*(beta_e3-beta_start);

	     ds_total=ds_total+sqrt(ds_squared);
	     escape=true;
	     beta_exit=beta_e3;
	     alpha_exit=alpha_e3;
     }

     if( land_e1 )NextT=Triangles[Tstart].Get1();
     if( land_e2 )NextT=Triangles[Tstart].Get2();
     if( land_e3 )NextT=Triangles[Tstart].Get3();

     qStart=Triangles[Tstart].GetQuad();
     qNext=Triangles[Tstart].GetQuad();

     // edge 1 always crosses into an edge 1 in the opposite sense
   /*  if(land_e1){
	     alphaNext=1.0-alpha_e1;
	     betaNext=0.0; */


/*
 * alpha_a=0.0;
	     beta_a=0.0;
	     alpha_b=1.0;
	     beta_b=0.0;
	     alpha_a_dash=alpha_b
	     beta_a_dash=beta_b;  

      }

 /*     if(land_e2){
	      if(qNext==qStart){
	          betaNext=1.0-beta_e2;
	          alphaNext=0.0;
	      }
	      else
              {
		   //crosses to edge 3 of neighbour
		   alphaNext=1.0-alpha_e2;
		   betaNext=alpha_e2
	      }
      }

     
      if(land_e3){
	      if(qNext==qStart){
		  alphaNext=1.0-alpha_e3;
	          betaNext=alphaa_e2;
	      }
	      else
              {
		   //crosses to edge 3 of neighbour -- has same sense
		   alphaNext=alpha_e3;
		   betaNext=beta_e3
	      }
      }  */
    }
    else
    {
	    cout << "This code only propagates a geodesic if ndiv=4" << endl;
    }

 
 while(!quitit){
        
       while(SDL_PollEvent(&event)){

          switch(event.type){
               case SDL_QUIT:
                 quitit=true;
                 break;
                 case SDL_MOUSEBUTTONDOWN:
                    mousedown=true;
                 break;
                 case SDL_MOUSEBUTTONUP:
                    mousedown=false;
                 break;
                 case SDL_MOUSEMOTION:
                  if(mousedown){
                         if(MouseOn)Camera1.MouseView();}
                  else{
                         if(MouseOn)Camera1.MouseLookAt(); }
                 break;  


               case SDL_KEYDOWN:
                   whatkey=&event.key.keysym;
                   HandleKeyPress(whatkey);
                   break;
               case SDL_KEYUP:
                   whatkey=&event.key.keysym;
                   HandleKeyRelease(whatkey);
               default:
                 break;
                     } // end of case
                } //end of inner loop
              CheckMove(Camera1);
              RenderScene(Camera1);
            } //end of outer loop

}
Пример #11
0
/******************* WAD restoration **********************/
void HDRrestoreWAD(const char *wadres)
{ struct WADINFO rwad;
  Int32 dirpos,ntry,n;
  Int32 rwadstart=0,rwadsize=0;
  Int32 ewadstart=0,ewadsize=0;
  static char ewadname[8];
  static char ewadfile[40];
  char  *data;
  Int32      size=0,wsize=0,sz=0;
  Int32 time;
  FILE *fp;
  Bool Fail;
  Phase("ME22", "Attempting to restore wad %s", fname (wadres));
  /*open DOOM.WAD*/
  rwad.ok=0;
  WADRopenR(&rwad,wadres);

  /*get position of fake directory entry, reference to old dir*/
  dirpos = rwad.dirpos - HDRdirSz;
  WADRseek(&rwad,dirpos);
  WADRreadBytes(&rwad,(char  *)HDRdir,HDRdirSz);
  Fail=FALSE;
  if(peek_i32_le (&HDRdir[0].start) != 0x24061968L)  Fail=TRUE;
  if(peek_i32_le (&HDRdir[0].size)  != 666L)         Fail=TRUE;
  if(strncmp(HDRdir[0].name,"IZNOGOOD",8)!=0)       Fail=TRUE;
  if(Fail != FALSE)
  { if((n=WADRfindEntry(&rwad,"_DEUTEX_"))>=0)
      if(rwad.dir[n].size>=HDRdirSz)
	{ dirpos=rwad.dir[n].start;
	  WADRseek(&rwad,dirpos);
	  WADRreadBytes(&rwad,(char  *)HDRdir,HDRdirSz);
	  Fail=FALSE;
	  if(peek_i32_le (&HDRdir[0].start) != 0x24061968L)  Fail=TRUE;
	  if(peek_i32_le (&HDRdir[0].size)  != 666L)         Fail=TRUE;
	  if(strncmp(HDRdir[0].name,"IZNOGOOD",8)!=0) Fail=TRUE;
	}
  }
  if(Fail != FALSE) ProgError("ME25", "Not a modified WAD");
  Phase("ME28", "Restoration infos seem correct");
  dirpos = peek_i32_le (&HDRdir[1].start);
  ntry   = peek_i32_le (&HDRdir[1].size);
  rwadstart = peek_i32_le (&HDRdir[2].start);
  rwadsize  = peek_i32_le (&HDRdir[2].size);
  ewadstart = peek_i32_le (&HDRdir[3].start);
  ewadsize  = peek_i32_le (&HDRdir[3].size);
  Normalise(ewadname,HDRdir[3].name);   /*name of WAD inside*/
  /*original file time*/
  time   = peek_i32_le (&HDRdir[4].size);
  if(peek_i32_le (&HDRdir[4].start)!=FALSE)
  { /*extract the PWAD*/
    sprintf(ewadfile,"%.8s.WAD",ewadname);
#if DT_OS == 'd'
#elif DT_OS == 'o'
    ToLowerCase(ewadfile);
#else
    ToLowerCase(ewadfile);
#endif
    fp=fopen(ewadfile,FOPEN_RB);
    if(fp!=NULL)
    { fclose(fp);
      Info("ME31", "%s already exists, internal WAD discarded",
	  fname (ewadfile));
    }
    else
    { Phase("ME34", "Restoring internal wad %s", fname (ewadfile));
      if((fp=fopen(ewadfile,FOPEN_WB))!=NULL)
      { data = (char  *)Malloc( MEMORYCACHE);
	size = ewadsize;
	WADRseek(&rwad,ewadstart);
	fseek(fp,0,SEEK_SET);
	for(wsize=0;wsize<size;wsize+=sz)
	{ sz=(size-wsize>MEMORYCACHE)? MEMORYCACHE : size-wsize;
	  WADRreadBytes(&rwad,data,sz);
	  errno = 0;
	  if(fwrite(data,(size_t)sz,1,fp)!=1)
	  { Warning("ME37", "%s: %s",
	      fnameofs (ewadfile, (long) ewadstart),
	      errno == 0 ? "write error" : strerror (errno));
	    break;
	  }
	}
	Free(data);
	fclose(fp);
      }
      else
	Warning("ME40", "%s: %s", fname (ewadfile), strerror (errno));
    }
  }
  WADRopenA(&rwad,wadres);
  /*correct the directory reference of DOOM.WAD*/
  WADRsetDirRef(&rwad,ntry,dirpos);
  /*restore original size*/
  WADRchsize(&rwad,rwadstart+rwadsize);
  WADRclose(&rwad);
  SetFileTime(wadres,time);
  Output("Restoration of %s should be successful\n", fname (wadres));
}
/*------------------------------------------------------------------------
 * Display call back
 *
 *  Input: none
 *  Output:
 *   it will draw a box (which is the same size as the brain) and a yellow
 *   sphere, if no datafile is specified (when running ./stereoTest -stereo)
 *
 *   Otherwise, it will draw a box and a brain. 
 *   (when running ./stereoTest -stereo -f ./test.data)
 *
 *   The model is set to be behind the screen when it is first loaded.
 */
static void draw(void)
{
    XYZ r;
    double ratio, radians, wd2, ndfl;
    double left, right, top, bottom;

    /* Clip to avoid extreme stereo */
    double near = camera.focallength / 5;
    double far = (Yminmax[1]-Yminmax[2]) * 40.0;

    /* Misc stuff */
    ratio = camera.screenwidth / (double) camera.screenheight;
    radians = DTOR * camera.aperture / 2.;
    wd2 = near * tan(radians);
    ndfl = near / camera.focallength;

    /* Clear the buffers */
    glDrawBuffer(GL_BACK_LEFT);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glDrawBuffer(GL_BACK_RIGHT);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    /* Derive the two eye positions */
    CROSSPROD(camera.vd, camera.vu, r);
    Normalise(&r);
    r.x *= camera.eyesep / 2.0;
    r.y *= camera.eyesep / 2.0;
    r.z *= camera.eyesep / 2.0;

    // left eye
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();

    left = -ratio * wd2 - 0.5 * camera.eyesep * ndfl;
	right = ratio * wd2 - 0.5 * camera.eyesep * ndfl;
	top = wd2;
	bottom = -wd2;
	glFrustum(left, right, bottom, top, near*2, far);

	glMatrixMode(GL_MODELVIEW);
	glDrawBuffer(GL_BACK_RIGHT);
	glLoadIdentity();
	gluLookAt(camera.vp.x + r.x, camera.vp.y + r.y, camera.vp.z + r.z,
		camera.vp.x + r.x + camera.vd.x,
		camera.vp.y + r.y + camera.vd.y,
		camera.vp.z + r.z + camera.vd.z,
		camera.vu.x, camera.vu.y, camera.vu.z);
        do_draw();

    // right eye
        glMatrixMode(GL_PROJECTION);
        glLoadIdentity();

        left = -ratio * wd2 + 0.5 * camera.eyesep * ndfl;
	right = ratio * wd2 + 0.5 * camera.eyesep * ndfl;
	top = wd2;
	bottom = -wd2;
	glFrustum(left, right, bottom, top, near*2, far);

	glMatrixMode(GL_MODELVIEW);
	glDrawBuffer(GL_BACK_LEFT);
	glLoadIdentity();
	gluLookAt(camera.vp.x - r.x, camera.vp.y - r.y, camera.vp.z - r.z,
				camera.vp.x - r.x + camera.vd.x,
				camera.vp.y - r.y + camera.vd.y,
				camera.vp.z - r.z + camera.vd.z,
				camera.vu.x, camera.vu.y, camera.vu.z);
	do_draw();

    //glutSwapBuffers();
}
Пример #13
0
void RenderScene(CCam & Camera1)
{

       glClear(GL_COLOR_BUFFER_BIT  | GL_DEPTH_BUFFER_BIT);
       glLoadIdentity();

       //
       //camera  pos      view     up vector
       gluLookAt(
        Camera1.CamPos.GetX(),   Camera1.CamPos.GetY(),  Camera1.CamPos.GetZ(),
        Camera1.CamView.GetX(), Camera1.CamView.GetY(), Camera1.CamView.GetZ(),
        Camera1.CamUp.GetX(),   Camera1.CamUp.GetY(),   Camera1.CamUp.GetZ());   


      //create fonts here
      //Check in Camera.h
      //Camera at (0,0,-5000)
      // stare at (0,0,0)

      //camera angle is 45 degees
      //camera 5000 away
      //-2000. is where xmin will be
      //+2000. is where xmax will be
      //
      //bounding box
 
       double exmin, whymin, zedmin;
       double exmax, whymax, zedmax;
       double exrange, whyrange,zedrange;
       exrange=xrange; whyrange=yrange; zedrange=zrange; 
       exmin=xmin, whymin=ymin; zedmin=zmin;


         double Halfscreen=3000.0;
         double Screen=2.*Halfscreen;
         double maxrange;
         maxrange=exrange;
         if(maxrange < whyrange)maxrange=whyrange;
         if(maxrange < zedrange)maxrange=zedrange;

         double Halfscreenx,Halfscreeny,Halfscreenz;
         Halfscreenx=Halfscreen*exrange/maxrange;
         Halfscreeny=Halfscreen*whyrange/maxrange;
         Halfscreenz=Halfscreen*zedrange/maxrange;
     

	 double x1,y1,z1;
	 double x2,y2,z2;
	 double x3,y3,z3;
	 double x4,y4,z4;
	 

      // materials
      float mat_spec[]={1.0, 0.0, 0.0, 0.0};  //polygon's ref of specular light
      float mat_diff[]={1.0, 0.0, 0.0, 0.0};  //polygon's ref of diffuse light
      float mat_amb[]={1.0, 0.0, 0.0, 0.0};  //polygon's ref of ambient light
      float mat_shine[]= {2.0};  //polygon's specular reflection
    // 0.0 to 128, small values give sharper specular reflection
      //lines
      float line_spec[]={0.0,0.0,0.0,1.0};  //line's ref of specular light
      float line_amb[]={0.0,0.0,0.0,1.0};  //line's ref of specular light
      float line_diff[]={0.0,0.0,0.0,0.0};  //line's ref of diffuse light
      float line_shine[]= {0.0};  //lines's sharpness of specular ref 

      glLineWidth(3.0);
      //  glColor3ub(255,0,0);  //(without lighting enabled)
      //


      double xvals[3],yvals[3],zvals[3];

      for(int i=istart; i<istop; i++){

		 int mi,mj,mk;
		 mi=Triangles[i].Get1();
		 mj=Triangles[i].Get2();
		 mk=Triangles[i].Get3();

                 int j=0;
                 xvals[j]=NodeV[ Triangles[i].Get1()].GetX();
                 yvals[j]=NodeV[ Triangles[i].Get1()].GetY();
                 zvals[j]=NodeV[ Triangles[i].Get1()].GetZ();
		 j=1;
                 xvals[j]=NodeV[ Triangles[i].Get2()].GetX();
                 yvals[j]=NodeV[ Triangles[i].Get2()].GetY();
                 zvals[j]=NodeV[ Triangles[i].Get2()].GetZ();
		 j=2;
                 xvals[j]=NodeV[ Triangles[i].Get3()].GetX();
                 yvals[j]=NodeV[ Triangles[i].Get3()].GetY();
                 zvals[j]=NodeV[ Triangles[i].Get3()].GetZ();

	      D3Dvec edge1, edge2,cross,normal;
	      edge1.SetX(xvals[1]-xvals[0]);
	      edge1.SetY(yvals[1]-yvals[0]);
	      edge1.SetZ(zvals[1]-zvals[0]);
	      edge2.SetX(xvals[2]-xvals[0]);
	      edge2.SetY(yvals[2]-yvals[0]);
	      edge2.SetZ(zvals[2]-zvals[0]);

	      cross=edge1*edge2;
	      Normalise(cross);
	      glNormal3f( (float)cross.GetX(), cross.GetY(),cross.GetZ());


              float scaleit=3000.0;

      glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, mat_amb);
      glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, mat_spec);
      glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, mat_diff);
      glMaterialfv(GL_FRONT_AND_BACK, GL_SHININESS, mat_shine);
              glPolygonMode(GL_FRONT_AND_BACK,GL_FILL);
	      glBegin(GL_TRIANGLES);
          	glVertex3f( scaleit*xvals[0], scaleit*yvals[0], scaleit*zvals[0] );
          	glVertex3f( scaleit*xvals[1], scaleit*yvals[1], scaleit*zvals[1] );
          	glVertex3f( scaleit*xvals[2], scaleit*yvals[2], scaleit*zvals[2] );
             glEnd(); 


	     scaleit=scaleit*1.001;



	      // DISASTER!
	      // Drawing a Quadric is VERY SLOW!
	      /*
      glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, mat_amb);
      glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, mat_spec);
      glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, mat_diff);
      glMaterialfv(GL_FRONT_AND_BACK, GL_SHININESS, mat_shine);
      gluQuadricTexture(QuadSphere,false);
      gluQuadricDrawStyle(QuadSphere,GL_FILL);
      gluSphere(QuadSphere, 0.95*scaleit, 20, 20);  */


      glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, line_spec);
      glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, line_amb);
      glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, line_spec);
      glMaterialfv(GL_FRONT_AND_BACK, GL_SHININESS, line_shine);

              glPolygonMode(GL_FRONT_AND_BACK,GL_LINE);
	      glBegin(GL_TRIANGLES);
          	glVertex3f( scaleit*xvals[0], scaleit*yvals[0], scaleit*zvals[0] );
          	glVertex3f( scaleit*xvals[1], scaleit*yvals[1], scaleit*zvals[1] );
          	glVertex3f( scaleit*xvals[2], scaleit*yvals[2], scaleit*zvals[2] );
             glEnd(); 
      }
      glPolygonMode(GL_FRONT_AND_BACK,GL_FILL);

      SDL_GL_SwapBuffers();

}
Пример #14
0
 /**
 * Sets the length of the vector.
 */
 void SetLength(T i_NewLength)
 {
     Normalise();
     *this *= i_NewLength;
 }
Пример #15
0
/*
   This is the basic display callback routine
   It creates the geometry, lighting, and viewing position
*/
void HandleDisplay(void)
{
	XYZ r;
   double ratio,radians,wd2,ndfl;
   double left,right,top,bottom;


   /* Misc stuff needed for the frustum */
   ratio   = camera.screenwidth / (double)camera.screenheight;
	if (camera.stereo == DUALSTEREO)
		ratio /= 2;
   radians = DTOR * camera.aperture / 2;
   wd2     = camera.near * tan(radians);
   ndfl    = camera.near / camera.focallength;
   top     =   wd2;
   bottom  = - wd2;

	/* Clear the buffers */
   if (camera.stereo == ACTIVESTEREO)
		ClearBuffers(2);
   else
		ClearBuffers(1);

	/* Determine the right eye vector */
   CROSSPROD(camera.vd,camera.vu,r);
   Normalise(&r);
   r.x *= camera.eyesep / 2.0;
   r.y *= camera.eyesep / 2.0;
   r.z *= camera.eyesep / 2.0;

	if (camera.stereo == ACTIVESTEREO || camera.stereo == DUALSTEREO) {

   	glMatrixMode(GL_PROJECTION);
   	glLoadIdentity();
      left  = - ratio * wd2 - 0.5 * camera.eyesep * ndfl;
      right =   ratio * wd2 - 0.5 * camera.eyesep * ndfl;
      glFrustum(left,right,bottom,top,camera.near,camera.far);
		if (camera.stereo == DUALSTEREO)
			glViewport(camera.screenwidth/2,0,camera.screenwidth/2,camera.screenheight);
		else
			glViewport(0,0,camera.screenwidth,camera.screenheight);
      glMatrixMode(GL_MODELVIEW);
      glDrawBuffer(GL_BACK_RIGHT);
      glLoadIdentity();
      gluLookAt(camera.vp.x + r.x,camera.vp.y + r.y,camera.vp.z + r.z,
                camera.vp.x + r.x + camera.vd.x,
                camera.vp.y + r.y + camera.vd.y,
                camera.vp.z + r.z + camera.vd.z,
                camera.vu.x,camera.vu.y,camera.vu.z);
		DrawGLScene();

      glMatrixMode(GL_PROJECTION);
      glLoadIdentity();
      left  = - ratio * wd2 + 0.5 * camera.eyesep * ndfl;
      right =   ratio * wd2 + 0.5 * camera.eyesep * ndfl;
      glFrustum(left,right,bottom,top,camera.near,camera.far);
      if (camera.stereo == DUALSTEREO)
         glViewport(0,0,camera.screenwidth/2,camera.screenheight);
      else
         glViewport(0,0,camera.screenwidth,camera.screenheight);
      glMatrixMode(GL_MODELVIEW);
      glDrawBuffer(GL_BACK_LEFT);
      glLoadIdentity();
      gluLookAt(camera.vp.x - r.x,camera.vp.y - r.y,camera.vp.z - r.z,
                camera.vp.x - r.x + camera.vd.x,
                camera.vp.y - r.y + camera.vd.y,
                camera.vp.z - r.z + camera.vd.z,
                camera.vu.x,camera.vu.y,camera.vu.z);
		DrawGLScene();


	} else {  //not stereo

      glMatrixMode(GL_PROJECTION);
      glLoadIdentity();
		glViewport(0,0,camera.screenwidth,camera.screenheight);
      left  = - ratio * wd2;
      right =   ratio * wd2;
      glFrustum(left,right,bottom,top,camera.near,camera.far);
      glMatrixMode(GL_MODELVIEW);
      glDrawBuffer(GL_BACK_LEFT);
      glLoadIdentity();
      gluLookAt(camera.vp.x,camera.vp.y,camera.vp.z,
                camera.vp.x + camera.vd.x,
                camera.vp.y + camera.vd.y,
                camera.vp.z + camera.vd.z,
                camera.vu.x,camera.vu.y,camera.vu.z);

		DrawGLScene();
	}

	/* Swap buffers */
	glutSwapBuffers();

}
Пример #16
0
void Sprites::Draw()
{
	static int i,j,k;
	static float M[16];
	static XYZ point;
	static float distancemult;
	static int lasttype;
	static int lastspecial;
	static int whichpatchx,whichpatchz;
	static XYZ start,end,colpoint;
	static bool check;
	static bool blend;
	static float tempmult;
	static XYZ difference;
	static float lightcolor[3];
	static float viewdistsquared=viewdistance*viewdistance;
	static XYZ tempviewer;

	tempviewer=viewer+viewerfacing*6;
	check=0;

	lightcolor[0]=light.color[0]*.5+light.ambient[0];
	lightcolor[1]=light.color[1]*.5+light.ambient[1];
	lightcolor[2]=light.color[2]*.5+light.ambient[2];

	checkdelay-=multiplier*10;

	if(checkdelay<=0){
		check=1;
		checkdelay=1;
	}

	lasttype=-1;
	lastspecial=-1;
	glEnable(GL_BLEND);
	glDisable(GL_LIGHTING);
	glDisable(GL_CULL_FACE);
	glEnable(GL_TEXTURE_2D);
	blend = 1;
	glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
	glDepthMask(0);
	glAlphaFunc(GL_GREATER, 0.0001);
	for(i=0;i<numsprites;i++){
		if(type[i]==cloudsprite&&lasttype!=type[i]){
			glBindTexture( GL_TEXTURE_2D, cloudtexture);
			if(!blend){
				blend=1;
				glAlphaFunc(GL_GREATER, 0.0001);
				glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
			}
		}
		if(type[i]==cloudimpactsprite&&lasttype!=type[i]){
			glBindTexture( GL_TEXTURE_2D, cloudimpacttexture);
			if(!blend){
				blend=1;
				glAlphaFunc(GL_GREATER, 0.0001);
				glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
			}
		}
		if(type[i]==breathsprite&&lasttype!=type[i]){
			glBindTexture( GL_TEXTURE_2D, cloudimpacttexture);
			if(!blend){
				blend=1;
				glAlphaFunc(GL_GREATER, 0.0001);
				glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
			}
		}
		if(type[i]==smoketype&&lasttype!=type[i]){
			glBindTexture( GL_TEXTURE_2D, smoketexture);
			if(!blend){
				blend=1;
				glAlphaFunc(GL_GREATER, 0.0001);
				glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
			}
		}
		if(type[i]==bloodsprite&&lasttype!=type[i]){
			glBindTexture( GL_TEXTURE_2D, bloodtexture);
			if(!blend){
				blend=1;
				glAlphaFunc(GL_GREATER, 0.0001);
				glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
			}
		}
		if(type[i]==splintersprite&&(lasttype!=type[i]||lastspecial!=special[i])){
			if(special[i]==0)glBindTexture( GL_TEXTURE_2D, splintertexture);
			if(special[i]==1)glBindTexture( GL_TEXTURE_2D, leaftexture);
			if(special[i]==2)glBindTexture( GL_TEXTURE_2D, snowflaketexture);
			if(special[i]==3)glBindTexture( GL_TEXTURE_2D, toothtexture);
			if(!blend){
				blend=1;
				glAlphaFunc(GL_GREATER, 0.0001);
				glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
			}
		}
		if(type[i]==snowsprite&&lasttype!=type[i]){
			glBindTexture( GL_TEXTURE_2D, snowflaketexture);
			if(!blend){
				blend=1;
				glAlphaFunc(GL_GREATER, 0.0001);
				glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
			}
		}
		if(type[i]==weaponshinesprite&&lasttype!=type[i]){
			glBindTexture( GL_TEXTURE_2D, shinetexture);
			if(blend){
				blend=0;
				glAlphaFunc(GL_GREATER, 0.001);
				glBlendFunc(GL_SRC_ALPHA,GL_ONE);
			}
		}
		if((type[i]==flamesprite||type[i]==weaponflamesprite)&&lasttype!=type[i]){
			glBindTexture( GL_TEXTURE_2D, flametexture);
			if(blend||lasttype==bloodflamesprite){
				blend=0;
				glAlphaFunc(GL_GREATER, 0.3);
				glBlendFunc(GL_SRC_ALPHA,GL_ONE);
			}
		}
		if((type[i]==bloodflamesprite)&&lasttype!=type[i]){
			glBindTexture( GL_TEXTURE_2D, bloodflametexture);
			if(blend){
				blend=0;
				glAlphaFunc(GL_GREATER, 0.3);
				glBlendFunc(GL_ONE,GL_ZERO);
				//glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
			}
		}
		if(type[i]!=snowsprite)distancemult=(viewdistsquared-(findDistancefast(&viewer,&position[i])-(viewdistsquared*fadestart))*(1/(1-fadestart)))/viewdistsquared;
		if(type[i]==snowsprite)distancemult=(144-(findDistancefast(&tempviewer,&position[i])-(144*fadestart))*(1/(1-fadestart)))/144;
		if(type[i]!=flamesprite){
			if(distancemult>=1)glColor4f(color[i][0]*lightcolor[0],color[i][1]*lightcolor[1],color[i][2]*lightcolor[2],opacity[i]);
			if(distancemult<1)glColor4f(color[i][0]*lightcolor[0],color[i][1]*lightcolor[1],color[i][2]*lightcolor[2],opacity[i]*distancemult);
		}
		if(type[i]==flamesprite){
			if(distancemult>=1)glColor4f(color[i][0],color[i][1],color[i][2],opacity[i]);
			if(distancemult<1)glColor4f(color[i][0],color[i][1],color[i][2],opacity[i]*distancemult);
		}
		lasttype=type[i];
		lastspecial=special[i];
		glMatrixMode(GL_MODELVIEW);							// Select The Modelview Matrix
		glPushMatrix();
			glTranslatef(position[i].x,position[i].y,position[i].z);
			if((type[i]==flamesprite||type[i]==weaponflamesprite||type[i]==weaponshinesprite)){
				difference=viewer-position[i];
				Normalise(&difference);
				glTranslatef(difference.x*size[i]/4, difference.y*size[i]/4, difference.z*size[i]/4);
			}
			if(type[i]==snowsprite){
				glRotatef(rotation[i]*.2,0,.3,1);
				glTranslatef(1,0,0);
			}
			glGetFloatv(GL_MODELVIEW_MATRIX,M);
			point.x=M[12];
			point.y=M[13];
			point.z=M[14];
			glLoadIdentity();
			glTranslatef(point.x, point.y, point.z);

			glRotatef(rotation[i],0,0,1);

			if((type[i]==flamesprite||type[i]==weaponflamesprite||type[i]==weaponshinesprite||type[i]==bloodflamesprite)){
				if(alivetime[i]<.14)glScalef(alivetime[i]/.14,alivetime[i]/.14,alivetime[i]/.14);
			}
			if(type[i]==smoketype||type[i]==snowsprite||type[i]==weaponshinesprite||type[i]==breathsprite){
				if(alivetime[i]<.3){
					if(distancemult>=1)glColor4f(color[i][0]*lightcolor[0],color[i][1]*lightcolor[1],color[i][2]*lightcolor[2],opacity[i]*alivetime[i]/.3);
					if(distancemult<1)glColor4f(color[i][0]*lightcolor[0],color[i][1]*lightcolor[1],color[i][2]*lightcolor[2],opacity[i]*distancemult*alivetime[i]/.3);
				}
			}
			if(type[i]==splintersprite&&special[i]>0&&special[i]!=3){
				if(alivetime[i]<.2){
					if(distancemult>=1)glColor4f(color[i][0]*lightcolor[0],color[i][1]*lightcolor[1],color[i][2]*lightcolor[2],alivetime[i]/.2);
					if(distancemult<1)glColor4f(color[i][0]*lightcolor[0],color[i][1]*lightcolor[1],color[i][2]*lightcolor[2],distancemult*alivetime[i]/.2);
				}
				else{
					if(distancemult>=1)glColor4f(color[i][0]*lightcolor[0],color[i][1]*lightcolor[1],color[i][2]*lightcolor[2],1);
					if(distancemult<1)glColor4f(color[i][0]*lightcolor[0],color[i][1]*lightcolor[1],color[i][2]*lightcolor[2],1);
				}
			}
			if(type[i]==splintersprite&&(special[i]==0||special[i]==3)){
				if(distancemult>=1)glColor4f(color[i][0]*lightcolor[0],color[i][1]*lightcolor[1],color[i][2]*lightcolor[2],1);
				if(distancemult<1)glColor4f(color[i][0]*lightcolor[0],color[i][1]*lightcolor[1],color[i][2]*lightcolor[2],1);
			}
			/*
			if(type[i]==snowsprite){
			glRotatef(rotation[i],0,0,1);
			glTranslatef(1,0,0);
			}*/

			glBegin(GL_TRIANGLES);
			glTexCoord2f(1.0f, 1.0f); glVertex3f( .5*size[i], .5*size[i], 0.0f);
			glTexCoord2f(0.0f, 1.0f); glVertex3f(-.5*size[i], .5*size[i], 0.0f);
			glTexCoord2f(1.0f, 0.0f); glVertex3f( .5*size[i],-.5*size[i], 0.0f);
			glTexCoord2f(0.0f, 0.0f); glVertex3f(-.5*size[i],-.5*size[i], 0.0f);
			glTexCoord2f(1.0f, 0.0f); glVertex3f( .5*size[i], -.5*size[i], 0.0f);
			glTexCoord2f(0.0f, 1.0f); glVertex3f(-.5*size[i], .5*size[i], 0.0f);
			glEnd();
		glPopMatrix();
	}
	tempmult=multiplier;
	for(i=numsprites-1;i>=0;i--){
		multiplier=tempmult;
		if(type[i]!=snowsprite)position[i]+=velocity[i]*multiplier;
		if(type[i]!=snowsprite)velocity[i]+=windvector*multiplier;
		if(type[i]==flamesprite||type[i]==smoketype)position[i]+=windvector*multiplier/2;
		if((type[i]==flamesprite||type[i]==weaponflamesprite||type[i]==weaponshinesprite||type[i]==bloodflamesprite))multiplier*=speed[i]*.7;
		alivetime[i]+=multiplier;

		if(type[i]==cloudsprite||type[i]==cloudimpactsprite){
			opacity[i]-=multiplier/2;
			size[i]+=multiplier/2;
			velocity[i].y+=gravity*multiplier*.25;
		}
		if(type[i]==breathsprite){
			opacity[i]-=multiplier/2;
			size[i]+=multiplier/2;
			if(findLength(&velocity[i])<=multiplier)velocity[i]=0;
			else{
				XYZ slowdown;
				slowdown=velocity[i]*-1;
				Normalise(&slowdown);
				slowdown*=multiplier;
				velocity[i]+=slowdown;
			}
		}
		if(type[i]==snowsprite){
			size[i]-=multiplier/120;
			rotation[i]+=multiplier*360;
			position[i].y-=multiplier;
			position[i]+=windvector*multiplier;
			if(position[i].y<tempviewer.y-6)position[i].y+=12;
			if(position[i].y>tempviewer.y+6)position[i].y-=12;
			if(position[i].z<tempviewer.z-6)position[i].z+=12;
			if(position[i].z>tempviewer.z+6)position[i].z-=12;
			if(position[i].x<tempviewer.x-6)position[i].x+=12;
			if(position[i].x>tempviewer.x+6)position[i].x-=12;
		}
		if(type[i]==bloodsprite){
			bool spritehit=0;
			rotation[i]+=multiplier*100;
			velocity[i].y+=gravity*multiplier;
			if(check){
				XYZ where,startpoint,endpoint,movepoint,footpoint;
				float rotationpoint;
				int whichtri;

				for(j=0;j<numplayers;j++){
					if(!spritehit&&player[j].dead&&alivetime[i]>.1){
						where=oldposition[i];
						where-=player[j].coords;
						if(!player[j].skeleton.free)where=DoRotation(where,0,-player[j].rotation,0);
						startpoint=where;
						where=position[i];
						where-=player[j].coords;
						if(!player[j].skeleton.free)where=DoRotation(where,0,-player[j].rotation,0);
						endpoint=where;

						movepoint=0;
						rotationpoint=0;
						whichtri=player[j].skeleton.drawmodel.LineCheck(&startpoint,&endpoint, &footpoint, &movepoint, &rotationpoint);
						if(whichtri!=-1){
							spritehit=1;
							player[j].DoBloodBigWhere(0,160,oldposition[i]);
							DeleteSprite(i);
						}
					}
				}

				whichpatchx=position[i].x/(terrain.size/subdivision*terrain.scale*terraindetail);
				whichpatchz=position[i].z/(terrain.size/subdivision*terrain.scale*terraindetail);
				if(whichpatchx>0&&whichpatchz>0&&whichpatchx<subdivision&&whichpatchz<subdivision)
					if(terrain.patchobjectnum[whichpatchx][whichpatchz]){
						if(!spritehit)
							for(j=0;j<terrain.patchobjectnum[whichpatchx][whichpatchz];j++){
								k=terrain.patchobjects[whichpatchx][whichpatchz][j];
								start=oldposition[i];
								end=position[i];
								if(!spritehit)
									if(objects.model[k].LineCheck(&start,&end,&colpoint,&objects.position[k],&objects.rotation[k])!=-1){
										if(detail==2||(detail==1&&abs(Random()%4)==0)||(detail==0&&abs(Random()%8)==0))objects.model[k].MakeDecal(blooddecalfast,DoRotation(colpoint-objects.position[k],0,-objects.rotation[k],0),size[i]*1.6/*+abs((float)(Random()%100))/2400*/,.5,Random()%360);
										DeleteSprite(i);
										spritehit=1;
									}	
							}
					}
					if(!spritehit)
						if(position[i].y<terrain.getHeight(position[i].x,position[i].z)){
							terrain.MakeDecal(blooddecalfast,position[i],size[i]*1.6/*+abs((float)(Random()%100))/2400*/,.6,Random()%360);
							DeleteSprite(i);
						}
			}
		}
		if(type[i]==splintersprite){
			rotation[i]+=rotatespeed[i]*multiplier;
			opacity[i]-=multiplier/2;
			if(special[i]==0||special[i]==2||special[i]==3)velocity[i].y+=gravity*multiplier;
			if(special[i]==1)velocity[i].y+=gravity*multiplier*.5;
		}
		if(type[i]==flamesprite||type[i]==weaponflamesprite||type[i]==weaponshinesprite||type[i]==bloodflamesprite){
			rotation[i]+=multiplier*rotatespeed[i];
			opacity[i]-=multiplier*5/4;
			if(type[i]!=weaponshinesprite&&type[i]!=bloodflamesprite)
				if(opacity[i]<.5&&opacity[i]+multiplier*5/4>=.5&&(abs(Random()%4)==0||(initialsize[i]>2&&Random()%2==0)))MakeSprite(smoketype, position[i],velocity[i], .9,.9,.6, size[i]*1.2, .4);
			if(alivetime[i]>.14&&(type[i]==flamesprite)){
				velocity[i]=0;
				velocity[i].y=1.5;
			}
		}
		/*if(type[i]==smoketype){
		opacity[i]-=multiplier/3/initialsize[i];
		size[i]+=multiplier;
		velocity[i]=0;
		velocity[i].y=1.5;
		rotation[i]+=multiplier*rotatespeed[i]/5;
		}*/
		if(type[i]==smoketype){
			opacity[i]-=multiplier/3/initialsize[i];
			color[i][0]-=multiplier;
			color[i][1]-=multiplier;
			color[i][2]-=multiplier;
			if(color[i][0]<.6)color[i][0]=.6;
			if(color[i][1]<.6)color[i][1]=.6;
			if(color[i][2]<.6)color[i][2]=.6;
			size[i]+=multiplier;
			velocity[i]=0;
			velocity[i].y=1.5;
			rotation[i]+=multiplier*rotatespeed[i]/5;
		}
		if(opacity[i]<=0||size[i]<=0)DeleteSprite(i);
	}
	if(check)
		for(i=numsprites-1;i>=0;i--){
			oldposition[i]=position[i];
		}
		glAlphaFunc(GL_GREATER, 0.0001);
		glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
}
Пример #17
0
/*
   Create the geometry
   - Create a surface
   - Turn it into an OpenGL list
*/
void MakeGeometry(void)
{
   int i,j,k,niter=1;
   double r,r1,r2,r3,dp,scale,offset;
   double len,sealevel = 0;
   COLOUR colour;
   XYZ p,p1,p2,p3,n;
   
   /* Do this for new surfaces  - zero the planet */
   if (geometrydirty == REALDIRTY) {
      for (i=0;i<3;i++) {
         for (j=0;j<nface;j++) {
            Normalise(&(faces[j].p[i]));
            faces[j].c[i] = 0;
         }
      }
      niter = iterationdepth;
      srand(seedvalue);
   }
   printf( "Generating -S %i -F %i %s\n", seedvalue, spheredepth, (whichmethod == 1 ? "--origin" : "--notorigin"));

   if (geometrydirty == REALDIRTY || geometrydirty == ADDONE) {

      /* Form the new surface */
      for (i=0;i<niter;i++) {

         /* Choose a random normal */
         n.x = drand48() - 0.5;
         n.y = drand48() - 0.5;
         n.z = drand48() - 0.5;
         Normalise(&n);
         offset = drand48() - 0.5;
   
         /* Purturb the points dependng on which side they are on */
         for (j=0;j<nface;j++) {
            for (k=0;k<3;k++) {
               if (whichmethod == 1) {
                  p = faces[j].p[k];
               } else {
                  p.x = faces[j].p[k].x - offset * n.x;
                  p.y = faces[j].p[k].y - offset * n.y;
                  p.z = faces[j].p[k].z - offset * n.z;
               }
               if ((dp = DotProduct(n,p)) > 0) 
                  faces[j].c[k]++;
               else 
                  faces[j].c[k]--; 
            }
         }
      }

      /* Adjust the heights */
      for (j=0;j<nface;j++) {
         for (k=0;k<3;k++) {
            Normalise(&(faces[j].p[k]));
            scale = 1 + deltaheight * faces[j].c[k];
            faces[j].p[k].x *= scale;
            faces[j].p[k].y *= scale;
            faces[j].p[k].z *= scale;
         }
      }
   }

   /* Find the range */
   radiusmin = 1;
   radiusmax = 1;
     for (i=0;i<nface;i++) {
      for (k=0;k<3;k++) {
           r = Modulus(faces[i].p[k]);
           radiusmin = MIN(radiusmin,r);
           radiusmax = MAX(radiusmax,r);
      }
     }
   radiusmin -= deltaheight;
   radiusmax += deltaheight;
   if (debug)
        fprintf(stderr,"Radius range %g -> %g\n",radiusmin,radiusmax);

   /* Create the opengl data */
   glNewList(1,GL_COMPILE);

   /* Draw the ocean sphere */
   if (showocean) {
      sealevel = radiusmin + (radiusmax - radiusmin) / 2;
      glColor3f(0.4,0.4,1.0);
      CreateSimpleSphere(origin,sealevel-0.01,60,0);
      radiusmin = sealevel;
   }

   glBegin(GL_TRIANGLES);
   for (i=0;i<nface;i++) {
      p1 = faces[i].p[0];
      r1 = Modulus(p1);
      p2 = faces[i].p[1];
      r2 = Modulus(p2);
      p3 = faces[i].p[2];
      r3 = Modulus(p3);
      if (r1 < sealevel && r2 < sealevel && r3 < sealevel)
         continue;

      colour = GetColour(r1,radiusmin,radiusmax,colourmap);
      glColor4f(colour.r,colour.g,colour.b,1.0);
      glNormal3f(p1.x,p1.y,p1.z);
      glVertex3f(p1.x,p1.y,p1.z);

      colour = GetColour(r2,radiusmin,radiusmax,colourmap);
      glColor4f(colour.r,colour.g,colour.b,1.0);
      glNormal3f(p2.x,p2.y,p2.z);
      glVertex3f(p2.x,p2.y,p2.z);

      colour = GetColour(r3,radiusmin,radiusmax,colourmap);
      glColor4f(colour.r,colour.g,colour.b,1.0);
      glNormal3f(p3.x,p3.y,p3.z);
      glVertex3f(p3.x,p3.y,p3.z);
   }
   glEnd();
   glEndList();
}
Пример #18
0
/** Select an action a, given state s and reward from previous action.

   Optional argument a forces an action if setForcedLearning() has
   been called with true.

   Two algorithms are implemented, both of which converge. One of them
   calculates the value of the current policy, while the other that of
   the optimal policy.

   Sarsa (\f$\lambda\f$) algorithmic description:

   1. Take action \f$a\f$, observe \f$r, s'\f$

   2. Choose \f$a'\f$ from \f$s'\f$ using some policy derived from \f$Q\f$

   3. \f$\delta = r + \gamma Q(s',a') - Q(s,a)\f$

   4. \f$e(s,a) = e(s,a)+ 1\f$, depending on trace settings

   5. for all \f$s,a\f$ :
   \f[
   Q_{t}(s,a) = Q_{t-1}(s,a) + \alpha \delta e_{t}(s,a),
   \f]
where \f$e_{t}(s,a) = \gamma \lambda e_{t-1}(s,a)\f$

	  end

   6. \f$a = a'\f$ (we will take this action at the next step)

   7. \f$s = s'\f$

   Watkins Q (l) algorithmic description:

   1. Take action \f$a\f$, observe \f$r\f$, \f$s'\f$

   2. Choose \f$a'\f$ from \f$s'\f$ using some policy derived from \f$Q\f$

   3. \f$a* = \arg \max_b Q(s',b)\f$

   3. \f$\delta = r + \gamma Q(s',a^*) - Q(s,a)\f$

   4. \f$e(s,a) = e(s,a)+ 1\f$, depending on eligibility traces

   5. for all \f$s,a\f$ :
\f[
        Q(s,a) = Q(s,a)+\alpha \delta e(s,a)
\f]
		if \f$(a'=a*)\f$ then \f$e(s,a)\f$ = \f$\gamma \lambda e(s,a)\f$
		           else \f$e(s,a) = 0\f$
	  end

   6. \f$a = a'\f$ (we will take this action at the next step)

   7. \f$s = s'\f$

   The most general algorithm is E-learning, currently under
   development, which is defined as follows:

   1. Take action \f$a\f$, observe \f$r\f$, \f$s'\f$

   2. Choose \f$a'\f$ from \f$s'\f$ using some policy derived from \f$Q\f$

   3. \f$\delta = r + \gamma E{Q(s',a^*)|\pi} - Q(s,a)\f$

   4. \f$e(s,a) = e(s,a)+ 1\f$, depending on eligibility traces

   5. for all \f$s,a\f$ :
\f[
        Q(s,a) = Q(s,a)+\alpha \delta e(s,a)
\f]
		\f$e(s,a)\f$ = \f$\gamma \lambda e(s,a) P(a|s,\pi) \f$

   6. \f$a = a'\f$ (we will take this action at the next step)

   7. \f$s = s'\f$

   Note that we also cut off the eligibility traces that have fallen below 0.1


*/
int DiscretePolicy::SelectAction (int s, real r, int forced_a)
{
    if ((s<0)||(s>=n_states)) {
        return 0;
    }

    if ((ps>=0)&&(pa>=0)) {
        expected_r += r;
        expected_V += Q[ps][pa];
        n_samples++;

        if (s==0) {
            real max_estimate = 0.0;
            real max_estimate_k = 0.0;
            for (int i=0; i<n_states; i++) {
                max_estimate += Q[i][argMax (Q[i])];
                max_estimate_k += 1.0;
            }

#if 0
            logmsg ("%f %f %f %f#rTVV\n",
                    expected_r/((real) n_samples),
                    temp,
                    expected_V/((real) n_samples),
                    max_estimate/max_estimate_k);
#endif
            expected_r = 0.0;
            expected_V= 0.0;
            n_samples = 0;
        }
    }
    int a, amax;
    int argmax = argMax (Q[s]);

    P[s][argmax] += zeta*(1.0f-P[s][argmax]);
    for (int j=0; j<n_actions; j++) {
        if (j!=argmax) {
            P[s][j] += zeta*(0.0f-P[s][j]);
        }
    }



    if (forced_learning) {
        a = forced_a;
    } else if (pursuit) {
        real sum = 0.0;
        a = -1;
        int j;
        for (j=0; j<n_actions; j++) {
            sum += P[s][j];
        }
        real X = urandom()*sum;
        real dsum=0.0;
        for (j=0; j<n_actions; j++) {
            dsum += P[s][j];
            if (X<=dsum) {
                a = j;
                break;
            }
        }
        if (a==-1) {
            fprintf (stderr, "No action selected with pursuit!\n");
        }
    } else if (confidence) {
        if (confidence_uses_gibbs && (confidence_distribution == SINGULAR)) {
            a = confMax (Q[s],vQ[s]);
        } else {
            a = confSample (Q[s], vQ[s]);
            if (confidence_uses_gibbs) { // and not SINGULAR distribution
                a = softMax(sample); //use softmax on the sample values
            }
        }
    } else if (reliability_estimate) {
        temp = sqrt(Sum(vQ[s], n_actions)/((real) n_actions));
        //temp = 0.1;
        a = softMax(Q[s]);
        //printf ("%f\n", temp);
    } else if (smax) {
        a = softMax (Q[s]);
        //printf ("Q[%d][%d]=%f\n", s, a, Q[s][a]);
    } else {
        a = eGreedy (Q[s]);
    }

    if (a<0 || a>=n_actions) {
        fprintf (stderr, "Action %d out of bounds.. ", a);
        a = (int) floor (urandom()*((real) n_actions));
        fprintf (stderr, "mapping to %d\n", a);
    }

    real EQ_s = 0.0;
    int i;

    switch (learning_method) {

    case Sarsa:
        amax = a;
        EQ_s = Q[s][amax];
        break;
    case QLearning:
        amax = argmax;
        EQ_s = Q[s][amax];
        break;
    case ELearning:
        amax = a; //? correct ?
        Normalise(eval, eval, n_actions);
        EQ_s = 0.0;
        for (i=0; i<n_actions; i++) {
            EQ_s += eval[i] * Q[s][i];
        }
        break;
    default:
        amax = a;
        EQ_s = Q[s][amax];
        fprintf (stderr, "Unknown learning method\n");
    }
    if ((ps>=0)&&(pa>=0)) { // do not update at start of episode
        real delta = r + gamma*EQ_s - Q[ps][pa];
        tdError = delta;
        if (replacing_traces) {
            e[ps][pa] = 1.0;
        } else {
            e[ps][pa] += 1.0;
        }
        real ad = alpha*delta;
        real gl = gamma * lambda;
        real variance_threshold = 0.0001f;
        if  (confidence_eligibility == false) {
            vQ[ps][pa] = (1.0f - zeta)*vQ[ps][pa] + zeta*(ad*ad);
            if (vQ[ps][pa]<variance_threshold) {
                vQ[ps][pa]=variance_threshold;
            }
        }
        if (ps<min_el_state) min_el_state = ps;
        if (ps>max_el_state) max_el_state = ps;


        for (i=0; i<n_states; i++) {
            //for (int i=min_el_state; i<=max_el_state; i++) {
            bool el=true;
            for (int j=0; j<n_actions; j++) {
                if (e[i][j]>0.01) {
                    Q[i][j] += ad * e[i][j];
                    if (confidence_eligibility == true) {
                        real zeta_el = zeta * e[i][j];
                        vQ[i][j] = (1.0f - zeta_el)*vQ[i][j] + zeta_el*(ad*ad);
                        if (vQ[i][j]<variance_threshold) {
                            vQ[i][j]=variance_threshold;
                        }
                    }
                    //this is the same as setting e[ps][pa] += (1-P[ps][pa])
                    // if P[][] remains unchanged between updates.
                    // -- removed because it doesn't work! --
                    //P[i][j] += 0.01*delta * e[i][j] * (1.-P[i][j]);
                    if ((fabs (Q[i][j])>1000.0)||(isnan(Q[i][j]))) {
                        printf ("u: %d %d %f %f\n", i,j,Q[i][j], ad * e[i][j]);
                    }

                    //This is only needed for Qlearning, but sarsa is not
                    //affected since always amax==a;
                    if (amax==a) {
                        e[i][j] *= gl;
                    } else {
                        e[i][j] = 0.0;
                    }
                } else {
                    e[i][j] = 0.0;
                    el = false;
                }
            }
            if (el==false) {
                if (min_el_state==i)
                    min_el_state++;
            } else {
                max_el_state = i;
            }
        }
    }

    //printf ("%d %d #STATE\n", min_el_state, max_el_state);
    //	printf ("Q[%d,%d]=%f r=%f e=%f ad=%f gl=%f #QV\n",
    //			ps, pa, Q[ps][pa], r, e[ps][pa], ad, gl);
    ps = s;
    pa = a;

    return a;
}
Пример #19
0
static void
TestBasic()
{
  WrapClock w;
  w.Reset();

  BrokenDate date = BrokenDate::Invalid();

  ok1(equals(Normalise(w, date, 0, 1), 60));
  ok1(!date.IsPlausible());

  ok1(equals(Normalise(w, date, 12, 0), 12 * 3600));
  ok1(!date.IsPlausible());

  /* time warp */
  ok1(equals(Normalise(w, date, 1, 0), 3600));
  ok1(!date.IsPlausible());

  /* seek right before midnight and produce a midnight wraparound */
  ok1(equals(Normalise(w, date, 23, 50), 23 * 3600 + 50 * 60));
  ok1(!date.IsPlausible());

  ok1(equals(Normalise(w, date, 0, 10), 24 * 3600 + 10 * 60));
  ok1(!date.IsPlausible());

  /* .. and another one */
  ok1(equals(Normalise(w, date, 23, 50), 47 * 3600 + 50 * 60));
  ok1(!date.IsPlausible());

  ok1(equals(Normalise(w, date, 0, 10), 48 * 3600 + 10 * 60));
  ok1(!date.IsPlausible());

  /* inject a valid date */
  date = BrokenDate(2013, 5, 14);
  BrokenDate expected_date = date;
  ok1(equals(Normalise(w, date, 0, 10), 48 * 3600 + 10 * 60));
  ok1(date == expected_date);

  /* same day */
  date = BrokenDate(2013, 5, 14);
  ok1(equals(Normalise(w, date, 0, 20), 48 * 3600 + 20 * 60));
  ok1(date == expected_date);

  /* next day */
  expected_date = date = BrokenDate(2013, 5, 15);
  ok1(equals(Normalise(w, date, 0, 10), 72 * 3600 + 10 * 60));
  ok1(date == expected_date);

  /* fast-forward 3 days */
  expected_date = date = BrokenDate(2013, 5, 18);
  ok1(equals(Normalise(w, date, 0, 10), 144 * 3600 + 10 * 60));
  ok1(date == expected_date);

  /* back one day */
  expected_date = date = BrokenDate(2013, 5, 17);
  ok1(equals(Normalise(w, date, 0, 10), 10 * 60));
  ok1(date == expected_date);

  /* fast-forward 2 days */
  expected_date = date = BrokenDate(2013, 5, 19);
  ok1(equals(Normalise(w, date, 0, 10), 48 * 3600 + 10 * 60));
  ok1(date == expected_date);

  /* back to invalid date */
  date = BrokenDate::Invalid();
  ok1(equals(Normalise(w, date, 0, 20), 48 * 3600 + 20 * 60));
  ok1(!date.IsPlausible());

  /* produce a wraparound and then recover date */
  ok1(equals(Normalise(w, date, 23, 50), 71 * 3600 + 50 * 60));
  ok1(equals(Normalise(w, date, 0, 10), 72 * 3600 + 10 * 60));
  ok1(equals(Normalise(w, date, 0, 20), 72 * 3600 + 20 * 60));
  ok1(!date.IsPlausible());

  expected_date = date = BrokenDate(2013, 5, 20);
  ok1(equals(Normalise(w, date, 0, 20), 72 * 3600 + 20 * 60));
  ok1(date == expected_date);

  /* back to invalid date, wraparound and then recover with warped
     date (resets the WrapClock) */
  date = BrokenDate::Invalid();
  ok1(equals(Normalise(w, date, 0, 20), 72 * 3600 + 20 * 60));
  ok1(equals(Normalise(w, date, 23, 50), 95 * 3600 + 50 * 60));
  ok1(equals(Normalise(w, date, 0, 10), 96 * 3600 + 10 * 60));
  ok1(!date.IsPlausible());

  expected_date = date = BrokenDate(2013, 5, 20);
  ok1(equals(Normalise(w, date, 0, 20), 20 * 60));
  ok1(date == expected_date);

  /* wrap midnight, but don't increment date - WrapClock must
     increment the date automatically */

  w.Reset();
  expected_date = date = BrokenDate(2013, 2, 28);
  ok1(equals(Normalise(w, date, 23, 55), 23 * 3600 + 55 * 60));
  ok1(date == expected_date);

  expected_date = BrokenDate(2013, 3, 1);
  ok1(equals(Normalise(w, date, 0, 5), 24 * 3600 + 5 * 60));
  ok1(date == expected_date);
}
Пример #20
0
void XTRgetEntry(const char *doomwad, const char *DataDir, const char *wadin,
    const char *entry, IMGTYPE Picture,SNDTYPE Sound,Bool fullSND, char trnR,
    char trnG, char trnB)
{ static struct WADINFO pwad;
  static struct WADINFO iwad;
  static char Name[8];
  Int16 e;
  char  *Entry; Int32 Entrysz;
  char  *Colors=NULL;
  Int16 insrX,insrY;
  char *extens=NULL;
  Bool Found=FALSE;

  Normalise(Name,entry);
  iwad.ok=0;
  WADRopenR(&iwad,doomwad);
   /*find PLAYPAL*/
  e=WADRfindEntry(&iwad,palette_lump);
  if(e>=0)
    Colors=WADRreadEntry(&iwad,e,&Entrysz);
  else
    ProgError("GE00", "%s: no %s lump in the iwad",
      fname (iwad.filename), lump_name (palette_lump));
  WADRclose(&iwad);
  pwad.ok=0;
  WADRopenR(&pwad,wadin);
  e=WADRfindEntry(&pwad,palette_lump);
  if(e>=0)
  {  Free(Colors);
     Colors=WADRreadEntry(&pwad,e,&Entrysz);
  }
  COLinit(trnR,trnG,trnB,Colors,(Int16)Entrysz, pwad.filename, palette_lump);
  Free(Colors);
  e=WADRfindEntry(&pwad,Name);
  if(e<0)
    ProgError("GE01", "%s: %s: lump not found",
	fname (pwad.filename), lump_name (entry));
  Phase("GE02", "%s: %s: extracting", fname (wadin), lump_name (entry));
  Entry=WADRreadEntry(&pwad,e,&Entrysz);
  /*try graphic*/
  if(Found!=TRUE)
    if(Entrysz>8)
    { switch(Picture)
      { case PICGIF: extens="GIF";break;
        case PICBMP: extens="BMP";break;
        case PICPPM: extens="PPM";break;
        case PICTGA: extens="TGA";break;
        default: Bug("GE03", "Invalid img type %d", (int) Picture);
      }
      MakeFileName(file,DataDir,"","",Name,extens);
      if(PICsaveInFile(file,PGRAPH,Entry,Entrysz,&insrX,&insrY,Picture, Name,
	  NULL) ==TRUE)
      { Info("GE04", "Picture insertion point is (%d,%d)",insrX,insrY);
        Found=TRUE;
      }
      /* FIXME try wall as well ? */
      else if((Entrysz==0x1000)||(Entrysz==0x1040))
      { if(PICsaveInFile(file,PFLAT,Entry,Entrysz,&insrX,&insrY,Picture, Name,
	  NULL) ==TRUE)
        { Found=TRUE;
        }
      }
      else if(Entrysz==64000L)
      { if(PICsaveInFile(file,PLUMP,Entry,Entrysz,&insrX,&insrY,Picture, Name,
	  NULL) ==TRUE)
        { Found=TRUE;
        }
      }
    }
  if (Found!=TRUE)
    if (peek_i16_le (Entry) == 3)
      if (Entrysz >= 8 + peek_i32_le (Entry + 4))
      { /*save as sound*/
        switch(Sound)
        { case SNDAU:  extens="AU";break;
          case SNDWAV: extens="WAV";break;
          case SNDVOC: extens="VOC";break;
          default: Bug("GE05", "Invalid snd type %d", (int) Sound);
        }
        MakeFileName(file,DataDir,"","",Name,extens);
        SNDsaveSound(file,Entry,Entrysz,Sound,fullSND, Name);
        Found=TRUE;
      }
  if(Found!=TRUE)
  { /*save as lump*/
    MakeFileName(file,DataDir,"","",Name,"LMP");
    WADRsaveEntry(&pwad,e,file);
  }
  Free(Entry);
  WADRclose(&pwad);
}
Пример #21
0
void RenderScene(CCam & Camera1)
{

       glClear(GL_COLOR_BUFFER_BIT  | GL_DEPTH_BUFFER_BIT);
       glLoadIdentity();

       //
       //camera  pos      view     up vector
       gluLookAt(
        Camera1.CamPos.GetX(),   Camera1.CamPos.GetY(),  Camera1.CamPos.GetZ(),
        Camera1.CamView.GetX(), Camera1.CamView.GetY(), Camera1.CamView.GetZ(),
        Camera1.CamUp.GetX(),   Camera1.CamUp.GetY(),   Camera1.CamUp.GetZ());   


      //create fonts here
      //Check in Camera.h
      //Camera at (0,0,-5000)
      // stare at (0,0,0)

      //camera angle is 45 degees
      //camera 5000 away
 

         double Halfscreen=3000.0;
         double Screen=2.*Halfscreen;

      // materials
      float mat_spec[]={1.0, 0.0, 0.0, 0.0};  //polygon's ref of specular light
      float mat_spec2[]={1.0, 1.0, 1.0, 0.0};  //polygon's ref of specular light
      float mat_diff[]={1.0, 0.0, 0.0, 0.0};  //polygon's ref of diffuse light
      float mat_diff2[]={1.0, 1.0, 1.0, 0.0};  //polygon's ref of diffuse light
      float mat_amb[]={1.0, 0.0, 0.0, 0.0};  //polygon's ref of ambient light
      float mat_amb2[]={1.0, 1.0, 1.0, 0.0};  //polygon's ref of ambient light
      float mat_shine[]= {2.0};  //polygon's specular reflection
    // 0.0 to 128, small values give sharper specular reflection
      //lines
      float line_spec[]={0.0,0.0,0.0,1.0};  //line's ref of specular light
      float line_amb[]={0.0,0.0,0.0,1.0};  //line's ref of specular light
      float line_diff[]={0.0,0.0,0.0,0.0};  //line's ref of diffuse light
      float line_shine[]= {0.0};  //lines's sharpness of specular ref 


      //For geodisic lines
      float geo_spec[]={0.0, 0.0, 1.0, 1.0};  //line's ref of specular light
      float geo_amb[]={0.0, 0.0, 1.0, 1.0};  //line's ref of ambient light
      float geo_diff[]={0.0, 0.0, 1.0, 0.0};  //line's ref of diffuse light
      float geo_shine[]= {0.0};  //lines's sharpness of specular ref 

      glLineWidth(3.0);
      //  glColor3ub(255,0,0);  //(without lighting enabled)
      //


      double xvals[3],yvals[3],zvals[3];
      float scaleit=3000.0;
      for(int i=istart; i<istop; i++){

		 int mi,mj,mk;
		 mi=Triangles[i].Get1();
		 mj=Triangles[i].Get2();
		 mk=Triangles[i].Get3();
		 //Transform to OpenGL coordinates

                 int j=0;
                 xvals[j]=NodeV[ Triangles[i].Get1()].GetX();
                 yvals[j]=NodeV[ Triangles[i].Get1()].GetZ();
                 zvals[j]=-NodeV[ Triangles[i].Get1()].GetY();
		 
		 j=1;
                 xvals[j]=NodeV[ Triangles[i].Get2()].GetX();
                 yvals[j]=NodeV[ Triangles[i].Get2()].GetZ();
                 zvals[j]=-NodeV[ Triangles[i].Get2()].GetY();
		 j=2;
                 xvals[j]=NodeV[ Triangles[i].Get3()].GetX();
                 yvals[j]=NodeV[ Triangles[i].Get3()].GetZ();
                 zvals[j]=-NodeV[ Triangles[i].Get3()].GetY();

	      D3Dvec edge1, edge2,cross,normal;
	      edge1.SetX(xvals[1]-xvals[0]);
	      edge1.SetY(yvals[1]-yvals[0]);
	      edge1.SetZ(zvals[1]-zvals[0]);
	      edge2.SetX(xvals[2]-xvals[0]);
	      edge2.SetY(yvals[2]-yvals[0]);
	      edge2.SetZ(zvals[2]-zvals[0]);

	      cross=edge1*edge2;

       /*       cout << "r1=" <<xvals[0] << "  " <<yvals[0] <<zvals[0] << endl;
              cout << "r2=" <<xvals[1] << "  " <<yvals[1] <<zvals[1] << endl;
              cout << "r3=" <<xvals[2] << "  " <<yvals[2] <<zvals[2] << endl;
              cout << "i=" << i << "  "<< Triangles[i].Get1()
                   <<  "  "  << Triangles[i].Get2()
                   <<  "  "  << Triangles[i].Get3() << endl;
              cout << "edge1=("
                   << edge1.GetX() <<"  "
                   << edge1.GetY() <<"  "
                   << edge1.GetZ() << " )"  << endl;
              cout << "edge2=("
                   << edge2.GetX() <<"  "
                   << edge2.GetY() <<"  "
                   << edge2.GetZ() << " )"  << endl;
              cout << "cross=("
                   << cross.GetX() <<"  "
                   << cross.GetY() <<"  "
                   << cross.GetZ() << " )"  << endl;  */

	      Normalise(cross);
	      glNormal3f( (float)cross.GetX(), cross.GetY(),cross.GetZ());

      glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, mat_amb);
      glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, mat_spec);
      glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, mat_diff);
      glMaterialfv(GL_FRONT_AND_BACK, GL_SHININESS, mat_shine);
      glPolygonMode(GL_FRONT_AND_BACK,GL_FILL);
	      glBegin(GL_TRIANGLES);
          	glVertex3f( scaleit*xvals[0], scaleit*yvals[0], scaleit*zvals[0] );
          	glVertex3f( scaleit*xvals[1], scaleit*yvals[1], scaleit*zvals[1] );
          	glVertex3f( scaleit*xvals[2], scaleit*yvals[2], scaleit*zvals[2] );
             glEnd(); 
      glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, line_spec);
      glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, line_amb);
      glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, line_spec);
      glMaterialfv(GL_FRONT_AND_BACK, GL_SHININESS, line_shine);
      glPolygonMode(GL_FRONT_AND_BACK,GL_LINE);
	      glBegin(GL_TRIANGLES);
          	glVertex3f( scaleit*xvals[0], scaleit*yvals[0], scaleit*zvals[0] );
          	glVertex3f( scaleit*xvals[1], scaleit*yvals[1], scaleit*zvals[1] );
          	glVertex3f( scaleit*xvals[2], scaleit*yvals[2], scaleit*zvals[2] );
             glEnd(); 
      }  

      scaleit=scaleit*1.01;

      glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, geo_spec);
      glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, geo_amb);
      glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, geo_spec);
      glMaterialfv(GL_FRONT_AND_BACK, GL_SHININESS, geo_shine);
      for(int i=0; i<Geokount-1; i++){
	      xvals[0]=Geodesy[i].GetX();
	      yvals[0]=Geodesy[i].GetZ();
	      zvals[0]=-Geodesy[i].GetY();

	      xvals[1]=Geodesy[i+1].GetX();
	      yvals[1]=Geodesy[i+1].GetZ();
	      zvals[1]=-Geodesy[i+1].GetY();
	      glBegin(GL_LINES);
          	glVertex3f( scaleit*xvals[0], scaleit*yvals[0], scaleit*zvals[0] );
          	glVertex3f( scaleit*xvals[1], scaleit*yvals[1], scaleit*zvals[1] );
	      glEnd();

	//      cout <<"kount=" << i << endl;
     // cout << "r1=" << xvals[0] << "  " << yvals[0] << "  " << zvals[0] << endl;  
     // cout << "r2=" << xvals[1] << "  " << yvals[1] << "  " << zvals[1] << endl;  
      }

      SDL_GL_SwapBuffers();

}
Пример #22
0
void EventLoop(CCam & Camera1)
{
 bool quitit=false;
 SDL_Event event;
 SDL_MouseMotionEvent event2;
 SDL_keysym  *whatkey;
 bool mousedown=false;

//  Go to while(!quitit) to see what happens once data set up

// Go to Render Scene for graphics bit

    bool exitnow=false;

    double xunit,yunit,zunit;
    xunit=1.0;yunit=1.0;zunit=1.0;


 //   if_stream opens for input
 //   of_stream opens for output
 //   f_stream opens for both
 //
    string filename ="Sphere4.dat";
    ifstream file_in;
    file_in.open(filename.c_str());
    
    file_in >> n_nodes  >> ntri;
    cout <<  n_nodes << "  number of nodes" << endl;
    cout <<  ntri<< "  number of triangles" << endl;
    cout << "read next line\n";


    cout << "start read loop\n";


    Triangles=(Triangle*)calloc(ntri, sizeof(Triangle));
    NodeV=(D3Dvec*)calloc(n_nodes, sizeof(D3Dvec));
    //initiales
    char quad, otherquad;

    int id,l,m,n;
    double x,y,z;

    for(int i=0; i<ntri;i++){
          file_in >>l;
          file_in >>m;
          file_in >>n;
          file_in >>quad;
          // same resuly of file_in >> l >>m >>n;

        Triangles[i]=Triangle();   //initialise
        Triangles[i].SetTri(l,m,n);
        Triangles[i].SetQuad(quad);
    }
     for(int i=0; i<ntri;i++){
        file_in >> l >> m >> n;
        Triangles[i].SetNeighb(l,m,n);
    }
    for(int i=0; i < n_nodes; i++){
          NodeV[i]=D3Dvec();
          file_in >> x >> y >> z;
          NodeV[i].SetVec(x,y,z);
     }

    istart=0;
    istop=ntri;
    
/**********************************************************************************
                   Calculate Metric Tensor
**********************************************************************************/
    double **Gmetric;
    Gmetric =(double**)calloc( ntri, sizeof( double[3] )  );
    if(!Gmetric){ cout << "Memory Failed for Gmetric " << endl; exit(0);}

    // 2D vectors in each triangle
    double **avec, **bvec;
    avec=(double**)calloc( ntri, sizeof(double[2]) );
    if(!avec){ cout << "Memory Failed for avec" << endl; exit(0);}

    bvec=(double**)calloc( ntri, sizeof(double[2]) );
    if(!bvec){ cout << "Memory Failed for bvec" << endl; exit(0);}

    double avecdash[2], bvecdash[2];
    double avecdash_new[2], bvecdash_new[2];

    D3Dvec Ve1,Ve2,VOrig;  //origin and edge vectors
    Ve1=D3Dvec();  Ve2=D3Dvec(); VOrig=D3Dvec(); //Initialise

    D3Dvec Unit_i, Unit_j, Unit_k;
    Unit_i=D3Dvec(); Unit_j=D3Dvec(); Unit_k=D3Dvec();

    int i1,i2,i3;

    double rad=-1;

    for(int i=0; i<ntri; i++){
    Gmetric[i]=new double[3];  //initialise
    i1=Triangles[i].Get1();
    i2=Triangles[i].Get2();
    i3=Triangles[i].Get3();
    x=NodeV[i1].GetX();
    y=NodeV[i1].GetY();
    z=NodeV[i1].GetZ();
    VOrig.SetVec(x,y,z);
    x=NodeV[i2].GetX()-VOrig.GetX();
    y=NodeV[i2].GetY()-VOrig.GetY();
    z=NodeV[i2].GetZ()-VOrig.GetZ();
    Ve1.SetVec(x,y,z);
    x=NodeV[i3].GetX()-VOrig.GetX();
    y=NodeV[i3].GetY()-VOrig.GetY();
    z=NodeV[i3].GetZ()-VOrig.GetZ();
    Ve2.SetVec(x,y,z);
    Gmetric[i][0]=Ve1.Dot(Ve1);
    Gmetric[i][1]=Ve1.Dot(Ve2);
    Gmetric[i][2]=Ve2.Dot(Ve2);
    rad=Gmetric[i][0];
    rad=sqrt(rad)*6370.;

     // local  cartesians
     Unit_i=Ve1;
     Normalise(Unit_i);
     Unit_k=Ve1*Ve2;
     Normalise(Unit_k);
     Unit_j=Unit_k*Unit_i;

     avec[i]=new double[2];
     bvec[i]=new double[2];

     avec[i][0]=Unit_i.Dot(Ve1);
     avec[i][1]=0.0;
     bvec[i][0]=Unit_i.Dot(Ve2);
     bvec[i][1]=Unit_j.Dot(Ve2);

    }  
    
/**********************************************************************************
     GEODESIC- start point
**********************************************************************************/

    // Now for a geodesic !
    //
    int Tstart0=56;
    int Tstart, TNext;
    double xO,yO,zO;
    double x1,y1,z1;
    double x2,y2,z2;
    double x3,y3,z3;
    char qStart,qNext;
    double  d1, d2, lambda;
    double d1dash,d2dash;
    double ds_total, ds_squared;
    double alpha_start, beta_start;

    double alphaTstart, betaTstart; 
//values of lambda to hit the line alpha=0, beta=0, alpha+beta=1
    double Tol1=0.000001;
    // if fabs(d) less than this it lands on edge miles
    // away or never at all
    double Tol2=1e-8;  //possibility that we land on a corner

    double alpha_e1, beta_e1;
    double alpha_e2, beta_e2;
    double alpha_e3, beta_e3;
    bool land_e1, land_e2, land_e3;
    double lambda_edge1, lambda_edge2, lambda_edge3;

    int Node1, Node2, Node3;

    double alphaNext,betaNext;
    double alpha_p, beta_p, alpha_q, beta_q;
    double alpha_p_dash, beta_p_dash, alpha_q_dash, beta_q_dash;

    double CosTheta,SinTheta,Theta,Phi;

    double adot_adash, adot_bdash, bdot_adash, bdot_bdash;

    double W1,W2,X1,X2,Y1,Y2,Z1,Z2,Det;
    double ex1,why1,ex2,why3;

    unsigned int ndim;

    int kount=0;
                              

    Tstart=Tstart0;
    alpha_start=0.25, beta_start=0.25;
    d1=.25; d2=0.19;  

    bool start_e1, start_e2, start_e3;
    start_e1=false;  //assume that for first triangle
    start_e2=false;  //we don't start off on an edge
    start_e3=false;  //change for instance, if we have alpha_start=0
/**********************************************************************************
     GEODESIC- Propagate
**********************************************************************************/

    while(ds_total < 6.3  && kount < GeoPos){
	    if(kount==GeoPos-1){
		    cout <<"Last One! " << endl;
			    }

    Node1=Triangles[Tstart].Get1();
    Node2=Triangles[Tstart].Get2();
    Node3=Triangles[Tstart].Get3();

    D3Dvec Rnode1,Rnode2;
    Rnode1=D3Dvec(); Rnode2=D3Dvec();

    xO=NodeV[Node1].GetX();
    yO=NodeV[Node1].GetY();
    zO=NodeV[Node1].GetZ();

    VOrig.SetVec(xO,yO,zO);

    x1=NodeV[Node2].GetX();
    y1=NodeV[Node2].GetY();
    z1=NodeV[Node2].GetZ();
    Rnode1.SetVec(x1,y1,z1);

    x2=NodeV[Node3].GetX();
    y2=NodeV[Node3].GetY();
    z2=NodeV[Node3].GetZ();
    Rnode2.SetVec(x2,y2,z2);

    Ve1=Rnode1-VOrig;
    Ve2=Rnode2-VOrig;

    x3=VOrig.GetX()+alpha_start*Ve1.GetX()+beta_start*Ve2.GetX();
    y3=VOrig.GetY()+alpha_start*Ve1.GetY()+beta_start*Ve2.GetY();
    z3=VOrig.GetZ()+alpha_start*Ve1.GetZ()+beta_start*Ve2.GetZ();


    Geodesy[kount]=new D3Dvec();
    Geodesy[kount].SetX(x3);
    Geodesy[kount].SetY(y3);
    Geodesy[kount].SetZ(z3);

    cout << Geodesy[kount].GetX() << "  "
	    << Geodesy[kount].GetY()
	    << "  " << Geodesy[kount].GetZ() 
	    << "  kount=" << kount <<
	     "   Tstart=" << Tstart << endl;
    kount++;


    land_e1=false; land_e2=false; land_e3=false;

    //alpha_start + d1 lambda=0 lands on edge2;
    //beta_start+ d2 lambda=0 lands on edge1;
     if( fabs(d1) > Tol1){lambda_edge1=-beta_start/d2; land_e1=true;}
     if( fabs(d2) > Tol1){lambda_edge2=-alpha_start/d1; land_e2=true;}
     if( fabs(d2+d2) > Tol1)
     {lambda_edge3=(1.0-alpha_start-beta_start)/(d1+d2); 
	     land_e3=true;}

     cout << "d1=" << d1 << endl;
     cout << "d2=" << d2 << endl;
     cout << "alpha_s=" << alpha_start << endl;
     cout << "beta_s=" << beta_start << endl;

     alpha_e1=alpha_start+lambda_edge1*d1;
     beta_e1=beta_start+lambda_edge1*d2;
     alpha_e2=alpha_start+lambda_edge2*d1;
     beta_e2=beta_start+lambda_edge2*d2;
     alpha_e3=alpha_start+lambda_edge3*d1;
     beta_e3=beta_start+lambda_edge3*d2;

     ndim=2;
     Dmatrix Mat(ndim,ndim);  //creates 4 by 3 on the heap.

     Dvector RHS(ndim);
     Dvector LHS(ndim);


     if(  (fabs(alpha_e1) < Tol2)  && (fabs(beta_e1) <Tol2) ){
		     // set it safely on edge 1
		     alpha_e1=2.*Tol2;
		     beta_e1=0.0;
		     }
     if(  (fabs(1.0-alpha_e1) < Tol2)  && (fabs(beta_e1) <Tol2) ){
		     // set it safely on edge 1
		     alpha_e1=1.0-2.0*Tol2;
		     beta_e1=0.0;
		     }

     if(  (fabs(alpha_e2) < Tol2)  && (fabs(beta_e2) <Tol2) ){
		     // set it safely on edge 2
		     alpha_e2=0.0;
		     beta_e2=2.0*Tol2;
		     }
     if(  (fabs(1.0-beta_e2) < Tol2)  && (fabs(alpha_e2) <Tol2) ){
		     // set it safely on edge 2
		     alpha_e2=0.0;
		     beta_e2=1.0-2.0*Tol2;
		     }

     if(  (fabs(1.0-alpha_e3-beta_e3) < Tol2)  ){
         if(fabs(alpha_e3) < Tol2){
		 // set it safely on edge 3
		 alpha_e3=2.0*Tol2;
		 beta_e3=1.0-alpha_e3;
	 }
         if(fabs(beta_e3) < Tol2){
		 // set it safely on edge 3
		 beta_e3=2.0*Tol2;
		 alpha_e3=1.0-beta_e3;
	 }
     }

   
/*     cout << "e1 " << alpha_e1 << "  L e1=" << lambda_edge1 << endl;
     cout << "e2 " << beta_e2 <<  "  L_e2=" <<  lambda_edge2 << endl;
     cout << "a e3 " << alpha_e3 << "  L_e3=" << lambda_edge3 << endl;
     cout << "b e3 " << beta_e3 << endl;  */

     if(lambda_edge1 <0.0 || alpha_e1 < 0.0 || alpha_e1 > 1.0)land_e1=false;
     if(lambda_edge2 <0.0 || beta_e2 < 0.0 || beta_e2 > 1.0)land_e2=false;

     if(lambda_edge3 <0.0 || alpha_e3 < 0.0 || alpha_e3 > 1.0)land_e3=false;
     if(lambda_edge3 <0.0 || beta_e3 < 0.0 || beta_e3 > 1.0)land_e3=false;

     cout << land_e1 << land_e2 << land_e3 << " edges 1 2 and 3" << endl;

     // Normally we land on two edges!
     // We start it some point in the start triangle
     // proceed to the edge, but now we start at an edge
     //
     if(start_e1)land_e1=false;
     if(start_e2)land_e2=false;
     if(start_e3)land_e3=false;
     
     start_e1=false;  
     start_e2=false; 
     start_e3=false; 

     if(land_e1){
	     //beta_e1=0
	     ds_squared=
	     Gmetric[Tstart][0]*(alpha_e1-alpha_start)*(alpha_e1-alpha_start)
	     -2.0*Gmetric[Tstart][1]*(alpha_e1-alpha_start)*beta_start
	     +Gmetric[Tstart][2]*beta_start*beta_start;

	     ds_total=ds_total+sqrt(ds_squared);
     }
     if(land_e2){
	     //alpha_e1=0
	     ds_squared=
	     Gmetric[Tstart][0]*alpha_start*alpha_start
	     -2.0*Gmetric[Tstart][1]*alpha_start*(beta_e2-beta_start)
	     +Gmetric[Tstart][2]*(beta_e2-beta_start)*(beta_e2-beta_start);

	     ds_total=ds_total+sqrt(ds_squared);
     }
     if(land_e3){
	     ds_squared=
	     Gmetric[Tstart][0]*(alpha_e3-alpha_start)*(alpha_e3-alpha_start)
	     +2.0*Gmetric[Tstart][1]*(alpha_e3-alpha_start)*(beta_e3-beta_start)
	     +Gmetric[Tstart][2]*(beta_e3-beta_start)*(beta_e3-beta_start);

	     ds_total=ds_total+sqrt(ds_squared);
     }

     if( land_e1 )TNext=Triangles[Tstart].GetN1();
     if( land_e2 )TNext=Triangles[Tstart].GetN2();
     if( land_e3 )TNext=Triangles[Tstart].GetN3();

     avecdash[0]=avec[TNext][0];
     avecdash[1]=avec[TNext][1];
     bvecdash[0]=bvec[TNext][0];
     bvecdash[1]=bvec[TNext][1];

     qStart=Triangles[Tstart].GetQuad();
     qNext=Triangles[TNext].GetQuad();

     // edge 1 always crosses into an edge 1 in the opposite sense
     if(land_e1){
	     alphaNext=1.0-alpha_e1;
	     betaNext=0.0; 
	     start_e1=true;


             alpha_p=0.0;    //edge 1 
	     beta_p=0.0;
	     alpha_q=1.0; 
	     beta_q=0.0;
	     alpha_p_dash=alpha_q;  // same edge, opposite sense
	     beta_p_dash=beta_q;  
	     alpha_q_dash=alpha_p;
	     beta_q_dash=beta_p;  

      }

     // If the neighbour on edge 2 is in a different quad
     // it lands on edge 3, otherwise minus edge 2
      if(land_e2){
              alpha_p=0.0;   
	      beta_p=0.0;
	      alpha_q=0.0;  
	      beta_q=1.0;


	      if(qNext==qStart){
		 //crosses to edge 2 of neighbour- opposite sense
	         betaNext=1.0-beta_e2;
	         alphaNext=0.0;
		 start_e2=true;

	         alpha_p_dash=alpha_q; 
	         beta_p_dash=beta_q;  
	         alpha_q_dash=alpha_p;
	         beta_q_dash=beta_p;  
	      }
	      else
              {
		 //crosses to edge 3 of neighbour- same sense.
		 alphaNext=1.0-beta_e2;
		 betaNext=beta_e2;
		 start_e3=true;

	         alpha_p_dash=1.0; 
	         beta_p_dash=0.0;  
	         alpha_q_dash=0.0;
	         beta_q_dash=1.0;  
	      }
      }
      

     
      if(land_e3){
	      alpha_p=1.0;
	      beta_p=0.0;
	      alpha_q=0.0;
	      beta_q=1.0;
	      if(qNext==qStart){
		 //crosses to edge 3 of neighbour- opposite sense.
		  alphaNext=1.0-alpha_e3;
	          betaNext=alpha_e3;
		  alpha_p_dash=alpha_q;
		  beta_p_dash=beta_q;
		  alpha_q_dash=alpha_p;
		  beta_q_dash=beta_p;
		  start_e3=true;
	      }
	      else
              {
		   //crosses to edge 2 of neighbour -- has same sense
		   alphaNext=0;
		   betaNext=beta_e3;

		   alpha_p_dash=0.0;
		   beta_p_dash=0.0;
		   alpha_q_dash=0.0;
		   beta_q_dash=1.0;
                   start_e2=true;
	      }
      }  
      cout << "ds_total=" << ds_total << endl;

      X1=alpha_p_dash*avecdash[0]+beta_p_dash*bvecdash[0];
      X2=alpha_p_dash*avecdash[1]+beta_p_dash*bvecdash[1];

      Y1=alpha_p*avec[Tstart][0]+beta_p*bvec[Tstart][0];
      Y2=alpha_p*avec[Tstart][1]+beta_p*bvec[Tstart][1];

      W1=alpha_q_dash*avecdash[0]+beta_q_dash*bvecdash[0];
      W2=alpha_q_dash*avecdash[1]+beta_q_dash*bvecdash[1];

      Z1=alpha_q*avec[Tstart][0]+beta_q*bvec[Tstart][0];
      Z2=alpha_q*avec[Tstart][1]+beta_q*bvec[Tstart][1];

      Det=(W2-X2)*(W2-X2)+(W1-X1)*(W1-X1);


      unsigned int ir,ic,ir1,ir2;
      ir=0; ic=0;
      Mat(ir,ic)=W1-X1;
      ir=0; ic=1;
      Mat(ir,ic)=W2-X2;
      ir=1; ic=0;
      Mat(ir,ic)=-(W2-X2);
      ir=1; ic=1;
      Mat(ir,ic)=W1-X1;

      Mat=Mat/Det;
      ir=0;
      RHS(ir)=Z1-Y1;
      ir=1;
      RHS(ir)=Z2-Y2;

      LHS=Mat*RHS;

      ir=0;
      CosTheta=LHS(ir);
      ir=1;
      SinTheta=LHS(ir);

     // cout << "cos and sin "<< CosTheta << "  " << SinTheta << endl; 
     // cout << "cossq+sinsq=" << CosTheta*CosTheta+SinTheta*SinTheta << endl;

      avecdash_new[0]=
	      avecdash[0]*CosTheta-avecdash[1]*SinTheta;
      avecdash_new[1]=
	      avecdash[0]*SinTheta+avecdash[1]*CosTheta;
      bvecdash_new[0]=
	      bvecdash[0]*CosTheta-bvecdash[1]*SinTheta;
      bvecdash_new[1]=
	      bvecdash[0]*SinTheta+bvecdash[1]*CosTheta;

      adot_adash=avec[Tstart][0]*avecdash_new[0]
	      +avec[Tstart][1]*avecdash_new[1];
      adot_bdash=avec[Tstart][0]*bvecdash_new[0]
	      +avec[Tstart][1]*bvecdash_new[1];
      bdot_adash=bvec[Tstart][0]*avecdash_new[0]
	      +bvec[Tstart][1]*avecdash_new[1];
      bdot_bdash=bvec[Tstart][0]*bvecdash_new[0]
	      +bvec[Tstart][1]*bvecdash_new[1];

      /*
      cout  << adot_adash << " a dot adash  "  <<
	      avec[Tstart][0]*avecdash_new[0]+
	      avec[Tstart][1]*avecdash_new[1]  << endl;

      cout << adot_bdash << " a dot bdash  "  << 
	      avec[Tstart][0]*bvecdash_new[0]+
	      avec[Tstart][1]*bvecdash_new[1]  << endl;

      cout << bdot_adash << " b dot adash  "   << 
	      bvec[Tstart][0]*avecdash_new[0]+
	      bvec[Tstart][1]*avecdash_new[1]  << endl;

      cout <<  bdot_bdash << " b dot bdash  "  <<
	      bvec[Tstart][0]*bvecdash_new[0]+
	      bvec[Tstart][1]*bvecdash_new[1]  << endl;
	      */

      // The next couts all check out

  /*    cout  <<  " a dot a  "  <<
	      avec[Tstart][0]*avec[Tstart][0]+
	      avec[Tstart][1]*avec[Tstart][1]  << endl;

      cout << " b dot b  "  << 
	      bvec[Tstart][0]*bvec[Tstart][0]+
	      bvec[Tstart][1]*bvec[Tstart][1]  << endl;

      cout <<  " a dot a in Next  "   << 
	      avec[TNext][0]*avec[TNext][0]+
	      avec[TNext][1]*avec[TNext][1]  << endl;

      cout << bdot_bdash << " b dot b  in Next "  <<
	      bvec[TNext][0]*bvec[TNext][0]+
	      bvec[TNext][1]*bvec[TNext][1]  << endl;

      cout << "a " <<  avec[Tstart][0] 
	               <<  "   " <<  avec[Tstart][1]   << endl;
      cout << "b " <<  bvec[Tstart][0] 
	               << "   " <<   bvec[Tstart][1]   << endl;
		       */
 
       
/*
      cout << "a dash " <<  avecdash[0] 
	               << "   " <<   avecdash[1]   << endl;
      cout << "b dash " <<   bvecdash[0] 
	               <<  "   " <<  bvecdash[1]   << endl;
		       */

 /*     cout << "a dash rotate " <<  avecdash_new[0] 
	               <<  "   " <<  avecdash_new[1]   << endl;
      cout << "b dash rotate " <<   bvecdash_new[0]  
	               <<  "   " <<  bvecdash_new[1]  << endl;
      */


      ir=0;ic=0;
      Mat(ir,ic)=Gmetric[Tstart][2];
      ir=0;ic=1;
      Mat(ir,ic)=-Gmetric[Tstart][1];
      ir=1;ic=0;
      Mat(ir,ic)=-Gmetric[Tstart][1];
      ir=1;ic=1;
      Mat(ir,ic)=Gmetric[Tstart][0];

      Det=Gmetric[Tstart][0]*Gmetric[Tstart][2]
         -Gmetric[Tstart][1]*Gmetric[Tstart][1];

      Mat=Mat/Det;

      ir=0;
      RHS(ir)=adot_adash;
      ir=1;
      RHS(ir)=bdot_adash;

      LHS=Mat*RHS;

      ir=0;
      x1=LHS(ir);
      ir=1;
      y1=LHS(ir);

      ir=0;
      RHS(ir)=adot_bdash;
      ir=1;
      RHS(ir)=bdot_bdash;

      LHS=Mat*RHS;

      ir=0;
      x2=LHS(ir);
      ir=1;
      y2=LHS(ir);

      //check adash=x1 a + y1 b, bdash=x2 a+ y2 b
      cout << x1*avec[Tstart][0]+y1*bvec[Tstart][0] 
	      << "  " << avecdash_new[0] << endl;
      cout << x1*avec[Tstart][1]+y1*bvec[Tstart][1]
	      << "  " << avecdash_new[1] << endl;
      cout << x2*avec[Tstart][0]+y2*bvec[Tstart][0]
	      << "  " << bvecdash_new[0] << endl;
      cout << x2*avec[Tstart][1]+y2*bvec[Tstart][1]
	      << "  " << bvecdash_new[1] << endl;
	      

      ir=0;ic=0;
      Mat(ir,ic)=y2;
      ir=0;ic=1;
      Mat(ir,ic)=-x2;
      ir=1;ic=0;
      Mat(ir,ic)=-y1;
      ir=1;ic=1;
      Mat(ir,ic)=x1;


      Det=x1*y2-x2*y1;

      Mat=Mat/Det;

      cout << "M11=" <<  y2/Det << "  M12=" << -x2/Det << endl;
      cout << "M21=" <<   -y1/Det << "  M12=" << x1/Det << endl;

      ir=0;
      RHS(ir)=d1;
      ir=1;
      RHS(ir)=d2;

      LHS=Mat*RHS;

      ir=0;
      d1dash=LHS(ir);
      ir=1;
      d2dash=LHS(ir);

      // We have finally arrived in TNext, which will be the new Tstart;
      Tstart=TNext;
      alpha_start=alphaNext;
      beta_start=betaNext;
      d1=d1dash;
      d2=d2dash;

    } //end while ds_total

    Geokount=kount;

    cout << "Geokount=" << Geokount << endl;


 while(!quitit){
        
       while(SDL_PollEvent(&event)){

          switch(event.type){
               case SDL_QUIT:
                 quitit=true;
                 break;
                 case SDL_MOUSEBUTTONDOWN:
                    mousedown=true;
                 break;
                 case SDL_MOUSEBUTTONUP:
                    mousedown=false;
                 break;
                 case SDL_MOUSEMOTION:
                  if(mousedown){
                         if(MouseOn)Camera1.MouseView();}
                  else{
                         if(MouseOn)Camera1.MouseLookAt(); }
                 break;  


               case SDL_KEYDOWN:
                   whatkey=&event.key.keysym;
                   HandleKeyPress(whatkey);
                   break;
               case SDL_KEYUP:
                   whatkey=&event.key.keysym;
                   HandleKeyRelease(whatkey);
               default:
                 break;
                     } // end of case
                } //end of inner loop
              CheckMove(Camera1);
              RenderScene(Camera1);
            } //end of outer loop

}
Пример #23
0
wxString Path::Normalise(const wxString &path){
#ifdef __WXMSW__
	//We only need to set this up once, and do it the first time
	if(DriveLabels.empty()){
		TCHAR drives[256];  
		if(GetLogicalDriveStrings(256, drives)){  
			LPTSTR drive = drives;
			int offset = _tcslen(drive) + 1;  
			while(*drive){  
				wxString volumename = wxEmptyString;
				TCHAR label[256]; 
				if(GetVolumeInformation(drive, label, sizeof(label), NULL, 0, NULL, NULL, 0)){
					volumename.Printf(wxT("%s"),label); 
					if(volumename != wxEmptyString){
						DriveLabels[volumename] = wxString(drive).Left(2);
					}
				}
				drive += offset;  
			}
		}
	}
#endif
	if(path.find("@") == wxNOT_FOUND){
		return path;
	}
	wxString token;
	wxString normalised = wxEmptyString;
	wxDateTime now = wxDateTime::Now();  
	wxStringTokenizer tkz(path, wxT("@"), wxTOKEN_RET_EMPTY_ALL);
	bool previousmatched = true;
    wxFileConfig config("", "", Locations::GetSettingsPath() + "variables.ini");
	while(tkz.HasMoreTokens()){
        token = tkz.GetNextToken();
		wxString strValue, read;
		if(token == "date"){
			token = now.FormatISODate();
			normalised += token;
			previousmatched = true;
		}
		else if(token == "time"){
			token = now.Format("%H") + "-" +  now.Format("%M");
			normalised += token;
			previousmatched = true;
		}
		else if(token == "YYYY" || token == "year"){
			token = now.Format("%Y");
			normalised += token;
			previousmatched = true;
		}
		else if(token == "MM" || token == "month"){
			token = now.Format("%m");
			normalised += token;
			previousmatched = true;
		}
		else if(token == "monthname"){
            token = wxDateTime::GetMonthName(wxDateTime::Now().GetMonth());
			normalised += token;
			previousmatched = true;
		}
		else if(token == "monthshortname"){
            token = wxDateTime::GetMonthName(wxDateTime::Now().GetMonth(), wxDateTime::Name_Abbr);
			normalised += token;
			previousmatched = true;
		}
		else if(token == "DD" || token == "day"){
			token = now.Format("%d");
			normalised += token;
			previousmatched = true;
		}
		else if(token == "dayname"){
            token = wxDateTime::GetWeekDayName(wxDateTime::Now().GetWeekDay());
			normalised += token;
			previousmatched = true;
		}
		else if(token == "dayshortname"){
            token = wxDateTime::GetWeekDayName(wxDateTime::Now().GetWeekDay(), wxDateTime::Name_Abbr);
			normalised += token;
			previousmatched = true;
		}
		else if(token == "hh" || token == "hour"){
			token = now.Format(wxT("%H"));
			normalised += token;
			previousmatched = true;
		}
		else if(token == "mm" || token == "minute"){
			token = now.Format("%M");
			normalised += token;
			previousmatched = true;
		}
		else if(token == "dayofweek"){
            int num = wxDateTime::Now().GetWeekDay();
            if(num == 0)
                num = 7;
            token = wxString::Format("%d", num);
			normalised += token;
			previousmatched = true;
		}
		else if(token == "weekofyear"){
            int num = wxDateTime::Now().GetWeekOfYear();
            token = wxString::Format("%d", num);
			normalised += token;
			previousmatched = true;
		}
		else if(token == wxT("drive")){
			normalised += wxPathOnly(wxStandardPaths::Get().GetExecutablePath()).Left(2);
			previousmatched = true;
		}
		else if(token == wxT("docs")){
			normalised += wxStandardPaths::Get().GetDocumentsDir();
			previousmatched = true;
		}
        else if(token == "username"){
            normalised += wxGetUserId();
            previousmatched = true;
        }
		else if(token == wxT("volume")){
			#ifdef __WXMSW__
				wxString name = wxEmptyString;
				WCHAR volumeLabel[256]; 
				GetVolumeInformation(wxPathOnly(wxStandardPaths::Get().GetExecutablePath()).Left(3), volumeLabel, sizeof(volumeLabel), NULL, 0, NULL, NULL, 0);
				name.Printf(wxT("%s"),volumeLabel); 
				normalised += name;
			#endif
			previousmatched = true;
		}
		else if(token == wxT("label")){
		 	wxFileConfig autorun("", "", wxPathOnly(wxStandardPaths::Get().GetExecutablePath()).Left(3) + wxFILE_SEP_PATH + wxT("autorun.inf"));
			wxString label = autorun.Read(wxT("Autorun/Label"));
			normalised += label;
			previousmatched = true;
		}
		else if(DriveLabels[token] != wxEmptyString){
			normalised += DriveLabels[token];
			previousmatched = true;
		}
		else if(wxGetEnv(token , &strValue)){
			normalised += strValue;
			previousmatched = true;
		}
		else if(config.HasGroup(token) && config.Read(token + wxT("/") + wxGetFullHostName(), &read)){
			normalised += read;
			previousmatched = true;
		}
		else if(config.HasGroup(token) && config.Read(token + wxT("/") + _("Other"), &read)){
			normalised += read;
			previousmatched = true;
		}
		else{
			if(previousmatched){
				normalised += token;
			}
			else{
				normalised = normalised + wxT("@") + token;
			}
			//This time we did not match
			previousmatched = false;
		}
	}
	if(normalised.Length() == 2 && normalised.Right(1) == wxT(":")){
		normalised += wxFILE_SEP_PATH;
	}
	wxFileName flReturn(normalised);
	if(flReturn.IsOk()){
		//If we havent made any changes in this run then return, else scan again
		//as new variables may have been added
		return normalised == path ? path : Normalise(normalised);
	}
	return wxEmptyString;
}
Пример #24
0
	Vector2 Math::Normalise(const Vector2& vec)
	{
		return Normalise(vec.GetX(),vec.GetY());
	}
Пример #25
0
/*
   This is the basic display callback routine
   It creates the geometry, lighting, and viewing position
   In this case it rotates the camera around the scene
*/
void Display(void)
{
   XYZ r,eyepos;
   double dist,ratio,radians,scale,wd2,ndfl;
   double left,right,top,bottom;

   /* Do we need to recreate the list ? */
   if (geometrydirty != NOTDIRTY) {
      MakeGeometry();
      geometrydirty = NOTDIRTY;
   }

   /* Clip to avoid extreme stereo */
   near = 0.1;
   far = 1000;
   if (stereo)
      near = camera.focallength / 5;

   /* Misc stuff */
   ratio  = camera.screenwidth / (double)camera.screenheight;
   radians = DTOR * camera.aperture / 2;
   wd2     = near * tan(radians);
   ndfl    = near / camera.focallength;

   /* Clear the buffers */
   glDrawBuffer(GL_BACK_LEFT);
   glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
   if (stereo) {
      glDrawBuffer(GL_BACK_RIGHT);
      glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
   }

   if (stereo) {

      /* Derive the two eye positions */
      CROSSPROD(camera.vd,camera.vu,r);
      Normalise(&r);
      r.x *= camera.eyesep / 2.0;
      r.y *= camera.eyesep / 2.0;
      r.z *= camera.eyesep / 2.0;
      eyepos = VectorAdd(camera.vp,r);

      glMatrixMode(GL_PROJECTION);
      glLoadIdentity();
      left  = - ratio * wd2 - 0.5 * camera.eyesep * ndfl;
      right =   ratio * wd2 - 0.5 * camera.eyesep * ndfl;
      top    =   wd2;
      bottom = - wd2;
      glFrustum(left,right,bottom,top,near,far);

      glMatrixMode(GL_MODELVIEW);
      glDrawBuffer(GL_BACK_RIGHT);
      glLoadIdentity();
      gluLookAt(eyepos.x,eyepos.y,eyepos.z,
                eyepos.x + camera.vd.x,
                eyepos.y + camera.vd.y,
                eyepos.z + camera.vd.z,
                camera.vu.x,camera.vu.y,camera.vu.z);
      MakeLighting();
      glCallList(1);

      eyepos = VectorSub(r,camera.vp);
      glMatrixMode(GL_PROJECTION);
      glLoadIdentity();
      left  = - ratio * wd2 + 0.5 * camera.eyesep * ndfl;
      right =   ratio * wd2 + 0.5 * camera.eyesep * ndfl;
      top    =   wd2;
      bottom = - wd2;
      glFrustum(left,right,bottom,top,near,far);

      glMatrixMode(GL_MODELVIEW);
      glDrawBuffer(GL_BACK_LEFT);
      glLoadIdentity();
      gluLookAt(eyepos.x,eyepos.y,eyepos.z,
                eyepos.x + camera.vd.x,
                eyepos.y + camera.vd.y,
                eyepos.z + camera.vd.z,
                camera.vu.x,camera.vu.y,camera.vu.z);
      MakeLighting();
      glCallList(1);

   } else {

      glMatrixMode(GL_PROJECTION);
      glLoadIdentity();
      left  = - ratio * wd2;
      right =   ratio * wd2;
      top    =   wd2;
      bottom = - wd2;
      glFrustum(left,right,bottom,top,near,far);

      glMatrixMode(GL_MODELVIEW);
      glDrawBuffer(GL_BACK_LEFT);
      glLoadIdentity();
      gluLookAt(camera.vp.x,camera.vp.y,camera.vp.z,
                camera.vp.x + camera.vd.x,
                camera.vp.y + camera.vd.y,
                camera.vp.z + camera.vd.z,
                camera.vu.x,camera.vu.y,camera.vu.z);
      MakeLighting();
      glCallList(1);
   }

   /* glFlush(); This isn't necessary for double buffers */
   glutSwapBuffers();

   if (record || windowdump) {
      WindowDump(camera.screenwidth,camera.screenheight,stereo);
      windowdump = FALSE;
   }

   if (demomode && iterationdepth < 1000) {
      iterationdepth++;
      geometrydirty = ADDONE;
      if (debug)
         fprintf(stderr,"Iteration: %d\n",iterationdepth);
   }
}
Пример #26
0
const char* FilePath::c_str() const
{
	Normalise();
	return m_storage.c_str();
}
Пример #27
0
void
vsVector2D::NormaliseSafe()
{
	if ( SqLength() > 0.f )
		Normalise();
}
Пример #28
0
void AddDecal(enum DECAL_ID decalID, VECTORCH *normalPtr, VECTORCH *positionPtr, int moduleIndex)
{
    DECAL *decalPtr;
    MATRIXCH orientation;
    int decalSize;
    int theta = FastRandom()&4095;
    int sin = GetSin(theta);
    int cos = GetCos(theta);


    MakeMatrixFromDirection(normalPtr,&orientation);

    if (decalID == DECAL_BULLETHOLE)
    {
        MakeImpactSmoke(&orientation,positionPtr);
    }

    decalPtr = AllocateDecal();

    decalPtr->DecalID = decalID;

    decalPtr->Centre = *positionPtr;

    if(DecalDescription[decalID].GrowthRate)
    {
        decalSize = ONE_FIXED;
        decalPtr->Direction[0].vx = MUL_FIXED(-decalSize,cos) - MUL_FIXED(-decalSize,sin);
        decalPtr->Direction[0].vy = MUL_FIXED(-decalSize,sin) + MUL_FIXED(-decalSize,cos);
        decalPtr->Direction[0].vz = DECAL_Z_OFFSET;
        RotateVector(&(decalPtr->Direction[0]),&orientation);
        Normalise(&(decalPtr->Direction[0]));

        decalPtr->Direction[1].vx = MUL_FIXED(decalSize,cos) - MUL_FIXED(-decalSize,sin);
        decalPtr->Direction[1].vy = MUL_FIXED(decalSize,sin) + MUL_FIXED(-decalSize,cos);
        decalPtr->Direction[1].vz = DECAL_Z_OFFSET;
        RotateVector(&(decalPtr->Direction[1]),&orientation);
        Normalise(&(decalPtr->Direction[1]));

        decalPtr->Direction[2].vx = MUL_FIXED(decalSize,cos) - MUL_FIXED(decalSize,sin);
        decalPtr->Direction[2].vy = MUL_FIXED(decalSize,sin) + MUL_FIXED(decalSize,cos);
        decalPtr->Direction[2].vz = DECAL_Z_OFFSET;
        RotateVector(&(decalPtr->Direction[2]),&orientation);
        Normalise(&(decalPtr->Direction[2]));

        decalPtr->Direction[3].vx = MUL_FIXED(-decalSize,cos) - MUL_FIXED(decalSize,sin);
        decalPtr->Direction[3].vy = MUL_FIXED(-decalSize,sin) + MUL_FIXED(decalSize,cos);
        decalPtr->Direction[3].vz = DECAL_Z_OFFSET;
        RotateVector(&(decalPtr->Direction[3]),&orientation);
        Normalise(&(decalPtr->Direction[3]));
        decalPtr->CurrentSize = DecalDescription[decalID].MinSize;
        decalPtr->TargetSize = DecalDescription[decalID].MaxSize;
        if (DecalDescription[decalID].CanCombine) decalPtr->TargetSize/=4;
    }
    else
    {
        decalSize = DecalDescription[decalID].MinSize;
        decalPtr->Vertices[0].vx = MUL_FIXED(-decalSize,cos) - MUL_FIXED(-decalSize,sin);
        decalPtr->Vertices[0].vy = MUL_FIXED(-decalSize,sin) + MUL_FIXED(-decalSize,cos);
        decalPtr->Vertices[0].vz = DECAL_Z_OFFSET;
        RotateVector(&(decalPtr->Vertices[0]),&orientation);
        decalPtr->Vertices[0].vx += positionPtr->vx;
        decalPtr->Vertices[0].vy += positionPtr->vy;
        decalPtr->Vertices[0].vz += positionPtr->vz;


        decalPtr->Vertices[1].vx = MUL_FIXED(decalSize,cos) - MUL_FIXED(-decalSize,sin);
        decalPtr->Vertices[1].vy = MUL_FIXED(decalSize,sin) + MUL_FIXED(-decalSize,cos);
        decalPtr->Vertices[1].vz = DECAL_Z_OFFSET;
        RotateVector(&(decalPtr->Vertices[1]),&orientation);
        decalPtr->Vertices[1].vx += positionPtr->vx;
        decalPtr->Vertices[1].vy += positionPtr->vy;
        decalPtr->Vertices[1].vz += positionPtr->vz;

        decalPtr->Vertices[2].vx = MUL_FIXED(decalSize,cos) - MUL_FIXED(decalSize,sin);
        decalPtr->Vertices[2].vy = MUL_FIXED(decalSize,sin) + MUL_FIXED(decalSize,cos);
        decalPtr->Vertices[2].vz = DECAL_Z_OFFSET;
        RotateVector(&(decalPtr->Vertices[2]),&orientation);
        decalPtr->Vertices[2].vx += positionPtr->vx;
        decalPtr->Vertices[2].vy += positionPtr->vy;
        decalPtr->Vertices[2].vz += positionPtr->vz;

        decalPtr->Vertices[3].vx = MUL_FIXED(-decalSize,cos) - MUL_FIXED(decalSize,sin);
        decalPtr->Vertices[3].vy = MUL_FIXED(-decalSize,sin) + MUL_FIXED(decalSize,cos);
        decalPtr->Vertices[3].vz = DECAL_Z_OFFSET;
        RotateVector(&(decalPtr->Vertices[3]),&orientation);
        decalPtr->Vertices[3].vx += positionPtr->vx;
        decalPtr->Vertices[3].vy += positionPtr->vy;
        decalPtr->Vertices[3].vz += positionPtr->vz;

    }

    decalPtr->ModuleIndex = moduleIndex;

    switch (decalID)
    {
    case DECAL_HUMAN_BLOOD:
    case DECAL_PREDATOR_BLOOD:
    case DECAL_ANDROID_BLOOD:
    {
        decalPtr->UOffset = (FastRandom()&1)*(32<<16);
        if (normalPtr->vy<-32768)
        {
            decalPtr->UOffset+=64<<16;
        }
        else
        {
            decalPtr->TargetSize = DecalDescription[decalID].MaxSize;
            decalPtr->CurrentSize = decalPtr->TargetSize-1;
        }
        break;
    }
    default:
    {
        decalPtr->UOffset = 0;
        break;
    }

    }

}
Пример #29
0
const Vector3d & Vector3d::Normalise()
{
	return Normalise(*this);
}
Пример #30
0
 CQuaternion::CQuaternion(const double dScalar, const CVector3D & oVector) {
    CLog("math","CQuaternion::Constructor (double,CVector3D)",LL_OBJECT);
    m_oVector = oVector;
    m_dScalar = dScalar;
    Normalise();
 } //CQuaternion(const double & dScalar, const CVector3D & oVector)