// Choose a planet around a star given it's index in the planetary system.
// The planetary system is either the system of the selected object, or the
// nearest planetary system if no object is selected.  If index is less than
// zero, pick the star.  This function should probably be in celestiacore.cpp.
void Simulation::selectPlanet(int index)
{
    if (index < 0)
    {
        if (selection.getType() == Selection::Type_Body)
        {
            PlanetarySystem* system = selection.body()->getSystem();
            if (system != NULL)
                setSelection(system->getStar());
        }
    }
    else
    {
        const Star* star = NULL;
        if (selection.getType() == Selection::Type_Star)
            star = selection.star();
        else if (selection.getType() == Selection::Type_Body)
            star = getSun(selection.body());

        SolarSystem* solarSystem = NULL;
        if (star != NULL)
            solarSystem = universe->getSolarSystem(star);
        else
            solarSystem = closestSolarSystem;

        if (solarSystem != NULL &&
            index < solarSystem->getPlanets()->getSystemSize())
        {
            setSelection(Selection(solarSystem->getPlanets()->getBody(index)));
        }
    }
}
////////////////////////////////////////////////////////////////////////////////
// Increment time
void StelCore::updateTime(double deltaTime)
{
	JDay+=timeSpeed*deltaTime;

	// Fix time limits to -100000 to +100000 to prevent bugs
	if (JDay>38245309.499988) JDay = 38245309.499988;
	if (JDay<-34803211.500012) JDay = -34803211.500012;

	if (position->isObserverLifeOver())
	{
		// Unselect if the new home planet is the previously selected object
		StelObjectMgr* objmgr = GETSTELMODULE(StelObjectMgr);
		Q_ASSERT(objmgr);
		if (objmgr->getWasSelected() && objmgr->getSelectedObject()[0].data()==position->getHomePlanet())
		{
			objmgr->unSelect();
		}
		StelObserver* newObs = position->getNextObserver();
		delete position;
		position = newObs;
	}
	position->update(deltaTime);

	// Position of sun and all the satellites (ie planets)
	SolarSystem* solsystem = (SolarSystem*)StelApp::getInstance().getModuleMgr().getModule("SolarSystem");
	solsystem->computePositions(getJDay(), position->getHomePlanet()->getHeliocentricEclipticPos());
}
Esempio n. 3
0
void Galaxy::setSolarSystems(QList<SolarSystem> solarSystems) {
    data->solarSystems.clear();
    for (int i = 0; i < solarSystems.size(); i++) {
        SolarSystem solarSystem = solarSystems.at(i);
        data->solarSystems.insert(solarSystem.getName(), solarSystem);
    }
}
Esempio n. 4
0
// Update the map for the given location.
void LocationDialog::setMapForLocation(const StelLocation& loc)
{
	// Avoids useless processing
	if (lastPlanet==loc.planetName)
		return;

	QPixmap pixmap;
	// Try to set the proper planet map image
	if (loc.planetName=="Earth")
	{
		// Special case for earth, we don't want to see the clouds
		pixmap = QPixmap(":/graphicGui/world.png");
	}
	else
	{
		SolarSystem* ssm = GETSTELMODULE(SolarSystem);
		PlanetP p = ssm->searchByEnglishName(loc.planetName);
		if (p)
		{
			QString path = StelFileMgr::findFile("textures/"+p->getTextMapName());
			if (path.isEmpty())
			{
				qWarning() << "ERROR - could not find planet map for " << loc.planetName;
				return;
			}
			pixmap = QPixmap(path);
		}
	}
	ui->mapLabel->setPixmap(pixmap);
	// For caching
	lastPlanet = loc.planetName;
}
Esempio n. 5
0
// adds a moon to the selected planet
void addMoon()
{
	// make a moon using random values
	solarSystem.addMoon(planetSelected, 
		(500 + random(1500)) * solarSystem.getRadiusOfPlanet(planetSelected),
		10 + random(100), 0.5 + random(20),
		solarSystem.getRadiusOfPlanet(planetSelected) * (0.05f + random(0.2f)), moon->getTextureHandle());
}
/**************************************************************************//**
 * @author Johnny Ackerman, Danial Andrus
 * 
 * @par Description:
 * Main function of the program. Passes control to the SolarSystem Class
 * 
 * 
 * @param[in]      argc - Number of aurments from the command line
 * @param[out]     argv - An array of command line aurgments
 * 
 * @returns 0 - program ran successfully.
 *****************************************************************************/
int main( int argc, char *argv[] )
{
	// Initialize program's core class
	SolarSystem solarsystem;

	// Run everything through the Fractals class
	return solarsystem.run( argc, argv);
}
Esempio n. 7
0
// -----------------------------------------------------------------------------------
// Version with JPL SolarSystem ephemeris. Throw if the SolarSystem is not valid
Matrix<double> SatelliteAttitude(const CommonTime& tt, const Position& SV,
                                 const SolarSystem& SSEph, const EarthOrientation& EO,
                                 double& sf)
   throw(Exception)
{
   if(SSEph.JPLNumber() == -1 || SSEph.startTime()-tt > 1.e-8
                              || tt - SSEph.endTime() > 1.e-8) {
      Exception e("Solar system ephemeris invalid");
      GPSTK_THROW(e);
   }

   return doSatAtt(tt,SV,SSEph,EO,sf);
}
Esempio n. 8
0
/*******************************************************************************
*
*   FUNCTION NAME:  getGravityObjectName
*
*------------------------ DETAILED FUNCTION DESCRIPTION ------------------------
*
*   Gets the name text for the object from the gravity system.
*
*******************************************************************************/
JNIEXPORT jstring Java_com_example_Gravity_Gravity_getGravityObjectName( JNIEnv* env, jobject obj, jint index )
{
   char * nameText = (char*)"Unknown";
   uint32_t textLength;
   uint32_t numObjects = mySolarSystem.getNumObjects();
   
   if ( ( index < numObjects ) && ( index >= 0 ) )
   {
   	mySolarSystem.getGravityObjectInfo( index, &nameText, &textLength );
   }

   return env->NewStringUTF(nameText);
}
Esempio n. 9
0
void RK4::integrate(std::valarray<double> &X, std::valarray<double> &V, double dt, SolarSystem mysystem, double G, double eps)
{
    std::valarray<double> k1(1,6*mysystem.numberOfBodies());
    std::valarray<double> k2(1,6*mysystem.numberOfBodies());
    std::valarray<double> k3(1,6*mysystem.numberOfBodies());
    std::valarray<double> k4(1,6*mysystem.numberOfBodies());

    // RK4 integration using vector X from solarysystem class.
    k1 = mysystem.calculateRK4(X, V, G, eps) * dt;
    k2 = mysystem.calculateRK4(X + 0.5 * k1, V, G, eps) * dt;
    k3 = mysystem.calculateRK4(X + 0.5 * k2, V, G, eps) * dt;
    k4 = mysystem.calculateRK4(X + k3, V, G, eps) * dt;
    X += (1.0/6) * (k1 + 2 * (k2 + k3) + k4);

}
Esempio n. 10
0
void LocationDialog::setFieldsFromLocation(const StelLocation& loc)
{	
	// Deactivate edit signals
	disconnectEditSignals();

	ui->cityNameLineEdit->setText(loc.name);
	int idx = ui->countryNameComboBox->findData(loc.country, Qt::UserRole, Qt::MatchCaseSensitive);
	if (idx==-1)
	{
		// Use France as default
		ui->countryNameComboBox->findData(QVariant("France"), Qt::UserRole, Qt::MatchCaseSensitive);
	}
	ui->countryNameComboBox->setCurrentIndex(idx);

	ui->longitudeSpinBox->setDegrees(loc.longitude);
	ui->latitudeSpinBox->setDegrees(loc.latitude);
	ui->altitudeSpinBox->setValue(loc.altitude);

	idx = ui->planetNameComboBox->findData(loc.planetName, Qt::UserRole, Qt::MatchCaseSensitive);
	if (idx==-1)
	{
		// Use Earth as default
		idx = ui->planetNameComboBox->findData(QVariant("Earth"), Qt::UserRole, Qt::MatchCaseSensitive);
	}
	ui->planetNameComboBox->setCurrentIndex(idx);
	setMapForLocation(loc);

	// Set pointer position
	ui->mapLabel->setCursorPos(loc.longitude, loc.latitude);

	ui->deleteLocationFromListPushButton->setEnabled(StelApp::getInstance().getLocationMgr().canDeleteUserLocation(loc.getID()));

	SolarSystem* ssm = GETSTELMODULE(SolarSystem);
	PlanetP p = ssm->searchByEnglishName(loc.planetName);
	LandscapeMgr* ls = GETSTELMODULE(LandscapeMgr);	
	if (ls->getFlagAtmosphereAutoEnable())
	{
		if (loc.planetName != StelApp::getInstance().getCore()->getCurrentLocation().planetName)
		{
			QSettings* conf = StelApp::getInstance().getSettings();
			ls->setFlagAtmosphere(p->hasAtmosphere() & conf->value("landscape/flag_atmosphere", true).toBool());
			ls->setFlagFog(p->hasAtmosphere() & conf->value("landscape/flag_fog", true).toBool());
		}
	}

	// Reactivate edit signals
	connectEditSignals();
}
Esempio n. 11
0
/*******************************************************************************
*
*   FUNCTION NAME:  getGravityObjectPosZ
*
*------------------------ DETAILED FUNCTION DESCRIPTION ------------------------
*
*
*******************************************************************************/
JNIEXPORT jdouble Java_com_example_Gravity_Gravity_getGravityObjectPosZ( JNIEnv* env, jobject obj, jint index )
{
   double retVal;
   
   retVal = mySolarSystem.getGravityObjectZ(index);

   return retVal;
}
Esempio n. 12
0
/*******************************************************************************
*
*   FUNCTION NAME:  getGravityNumObjects
*
*------------------------ DETAILED FUNCTION DESCRIPTION ------------------------
*
*
*******************************************************************************/
JNIEXPORT jint Java_com_example_Gravity_Gravity_getGravityNumObjects( JNIEnv* env, jobject obj )
{
   double retVal;
   
   retVal = mySolarSystem.getNumObjects();

   return retVal;
}
Esempio n. 13
0
// Update the map for the given location.
void LocationDialog::setMapForLocation(const StelLocation& loc)
{
	// Avoids usless processing
	if (lastPlanet==loc.planetName && lastVisionMode==StelApp::getInstance().getVisionModeNight())
		return;

	QPixmap pixmap;
	// Try to set the proper planet map image
	if (loc.planetName=="Earth")
	{
		// Special case for earth, we don't want to see the clouds
		pixmap = QPixmap(":/graphicGui/world.png");
	}
	else
	{
		SolarSystem* ssm = GETSTELMODULE(SolarSystem);
		PlanetP p = ssm->searchByEnglishName(loc.planetName);
		QString path;
		if (p)
		{
			try
			{
				path = StelFileMgr::findFile("textures/"+p->getTextMapName());
			}
			catch (std::runtime_error& e)
			{
				qWarning() << "ERROR - could not find planet map for " << loc.planetName << e.what();
				return;
			}
			pixmap = QPixmap(path);
		}
	}

	if (StelApp::getInstance().getVisionModeNight())
	{
		ui->mapLabel->setPixmap(StelButton::makeRed(pixmap));
	}
	else
	{
		ui->mapLabel->setPixmap(pixmap);
	}

	// For caching
	lastPlanet = loc.planetName;
	lastVisionMode = StelApp::getInstance().getVisionModeNight();
}
Esempio n. 14
0
bool Galaxy::collidesWithAnotherSystem(SolarSystem system) const {
    for (int i = 0; i < data->solarSystems.values().length(); i++) {
        const SolarSystem existingSystem = data->solarSystems.values().at(i);
        if (!(existingSystem.getX() + 32 < system.getX() || existingSystem.getX() > system.getX() + 32
                || existingSystem.getY() + 32 < system.getY() || existingSystem.getY() > system.getY() + 32)) {
            return true;
        }
    }
    return false;
}
Esempio n. 15
0
/*******************************************************************************
*
*   FUNCTION NAME:  computeNewPositions
*
*------------------------ DETAILED FUNCTION DESCRIPTION ------------------------
*
*   numIterationsPerDisplayPoint - number of iterations to compute.
*
*   computationTimeInterval      - time in seconds per computation interval
*
*
*   Computes a number of iterations of the gravitational interactions on the full system.
*
*******************************************************************************/
JNIEXPORT void Java_com_example_Gravity_Gravity_computeNewPositions( JNIEnv* env, jobject obj, jint numIterationsPerDisplayPoint, jdouble computationTimeInterval)
{
	uint32_t index;

	for(index=0;index<numIterationsPerDisplayPoint ; index++)
	{
		mySolarSystem.processTimeInterval(computationTimeInterval);
	}
}
Esempio n. 16
0
void RK4::integrateSolarSystem(SolarSystem &system, double dt, int sunCheck)
{
    // Creating vectors
    int n_bodies = system.numberOfBodies();

    std::vector<double> A  = std::vector<double>(4*n_bodies);
    std::vector<double> K1 = std::vector<double>(4*n_bodies);
    std::vector<double> K2 = std::vector<double>(4*n_bodies);
    std::vector<double> K3 = std::vector<double>(4*n_bodies);
    std::vector<double> K4 = std::vector<double>(4*n_bodies);

    // Setting up A
    /* vector A = [x1, y1, vx1, vy1,    (first body)
                   x2, y2, vx2, vy2,    (second body)
                   ... for all celestial bodies
    */
    for(int i=0;i<n_bodies;i++)
    {
        CelestialBody *body = system.bodies[i];
        A[4*i]  = body->position.x();
        A[4*i+1]= body->position.y();
        A[4*i+2]= body->velocity.x();
        A[4*i+3]= body->velocity.y();
    }

    // Runge-Kutta 4th order integration, start
    K1= dAdt(system,A);

    // Returning acceleration values to CelestialBody objects
    for(int i=0;i<n_bodies;i++)
    {
        CelestialBody *body = system.bodies[i];
        body->acceleration.set(K1[4*i+2], K1[4*i+3], 0);
    }

    // Runge-Kutta 4th order integration, continued
    K1 = mult(K1,dt);
    K2 = dAdt(system,add(A,mult(K1,1/2.0))); K2 = mult(K2,dt);
    K3 = dAdt(system,add(A,mult(K2,1/2.0))); K3 = mult(K3,dt);
    K4 = dAdt(system,add(A,K3))            ; K4 = mult(K4,dt);

    // Combining (K1 + 2*K2 + 2*K3 + K4)/6 into K1
    K1 = add(K1,K4);
    K1 = add(K1,mult(K2,2));
    K1 = add(K1,mult(K3,2));
    K1 = mult(K1,1/6.0);
    A = add(A,K1);

    // Returning new position and velocity values to CelestialBody objects
    for(int i=sunCheck;i<n_bodies;i++)  // For stationary Sun, set startpoint i=1
    {
        CelestialBody *body = system.bodies[i];
        body->position.set(A[4*i],   A[4*i+1], 0);
        body->velocity.set(A[4*i+2], A[4*i+3], 0);
    }
}
Esempio n. 17
0
//Deletes all of the created objects here.
void CloseFunc(){
	window.window_handle = -1;
	cylinder.TakeDown();torus.TakeDown();square.TakeDown();square2.TakeDown();
	disc.TakeDown();sphere.TakeDown();sphere2.TakeDown();tiger.TakeDown();goldeen.TakeDown();
	stadium.TakeDown();coin.TakeDown();ss.TakeDown();healthBar.TakeDown();
	shark.TakeDown();bird.TakeDown();sb.TakeDown();arena.TakeDown();skyboxUW.TakeDown();fbo.TakeDown();rain2.TakeDown();
	tri2.TakeDown();skybox.TakeDown();skybox2.TakeDown();skybox3.TakeDown();egg.TakeDown();snow2.TakeDown();
	star.TakeDown();magneton.TakeDown();haunter.TakeDown();frog.TakeDown();
	sph1.TakeDown(); enm.TakeDown(); usr.TakeDown();sq4.TakeDown();soldier.TakeDown();userTeam.TakeDown();cpuTeam.TakeDown();
}
Esempio n. 18
0
void LocationDialog::populatePlanetList()
{
	Q_ASSERT(ui);
	Q_ASSERT(ui->planetNameComboBox);

	QComboBox* planets = ui->planetNameComboBox;
	SolarSystem* ssystem = GETSTELMODULE(SolarSystem);
	QStringList planetNames(ssystem->getAllPlanetEnglishNames());

	//Save the current selection to be restored later
	planets->blockSignals(true);
	int index = planets->currentIndex();
	QVariant selectedPlanetId = planets->itemData(index);
	planets->clear();
	//For each planet, display the localized name and store the original as user
	//data. Unfortunately, there's no other way to do this than with a cycle.
	foreach(const QString& name, planetNames)
	{
		planets->addItem(q_(name), name);
	}
void SolarSystemBrowser::slotRefreshTree()
{
    Simulation* sim = appCore->getSimulation();
    
    // Update the browser with the solar system closest to the active observer
    SolarSystem* solarSys = sim->getUniverse()->getNearestSolarSystem(sim->getActiveObserver()->getPosition());

    // Don't update the solar system browser if no solar system is nearby
    if (!solarSys)
        return;

    Star* rootStar = solarSys->getStar();

    // We want to show all gravitationally associated stars in the
    // browser; follow the chain up the parent star or barycenter.
    while (rootStar->getOrbitBarycenter() != NULL)
    {
        rootStar = rootStar->getOrbitBarycenter();
    }

    bool groupByClass = groupCheckBox->checkState() == Qt::Checked;

    solarSystemModel->buildModel(rootStar, groupByClass);

    treeView->resizeColumnToContents(SolarSystemTreeModel::NameColumn);

    treeView->clearSelection();

    // Automatically expand stars in the model (to a max depth of 2)
    QModelIndex primary = solarSystemModel->index(0, 0, QModelIndex());
    if (primary.isValid() && solarSystemModel->objectAtIndex(primary).star() != NULL)
    {
        treeView->setExpanded(primary, true);
        QModelIndex secondary = solarSystemModel->index(0, 0, primary);
        if (secondary.isValid() && solarSystemModel->objectAtIndex(secondary).star() != NULL)
        {
            treeView->setExpanded(secondary, true);
        }
    }
    
}
Esempio n. 20
0
void Planet::sunPosition(qreal &lon, qreal &lat, const QDateTime &dateTime) const
{
    SolarSystem sys;
    sys.setCurrentMJD(
                dateTime.date().year(), dateTime.date().month(), dateTime.date().day(),
                dateTime.time().hour(), dateTime.time().minute(),
                (double)dateTime.time().second());
    const QString pname = d->id.at(0).toUpper() + d->id.right(d->id.size() - 1);
    QByteArray name = pname.toLatin1();
    sys.setCentralBody( name.data() );

    double ra = 0.0;
    double decl = 0.0;
    sys.getSun(ra, decl);

    double _lon = 0.0;
    double _lat = 0.0;
    sys.getPlanetographic(ra, decl, _lon, _lat);

    lon = _lon * DEG2RAD;
    lat = _lat * DEG2RAD;
}
Esempio n. 21
0
void SunLocator::updatePosition()
{
    QString planetId = d->m_planet->id();
    SolarSystem sys;

    QDateTime dateTime = d->m_clock->dateTime();
    sys.setCurrentMJD(
                dateTime.date().year(), dateTime.date().month(), dateTime.date().day(),
                dateTime.time().hour(), dateTime.time().minute(),
                (double)dateTime.time().second());
    QString const pname = planetId.at(0).toUpper() + planetId.right(planetId.size() - 1);
    QByteArray const name = pname.toLatin1();
    sys.setCentralBody( name.data() );

    double ra = 0.0;
    double decl = 0.0;
    sys.getSun( ra, decl );
    double lon = 0.0;
    double lat = 0.0;
    sys.getPlanetographic (ra, decl, lon, lat);
    d->m_lon = lon * DEG2RAD;
    d->m_lat = lat * DEG2RAD;
}
Esempio n. 22
0
/*
 * Main method takes a systemfile containing the setup of the system being
 * simulated, a dt and a T (how long the simulation is to run). All times are
 * in years.
 *
 * Usage:
 *   ./<exe> <dt> <T> <systemfile>
 */
int main(int argc, char* argv[]) {
  if (argc != 4) {
    cout << "Need step size and number of steps pluss file to fetch system from." << endl;
    return 1;
  }

  double dt = atof(argv[1]);
  double T = atof(argv[2]);
  double t = 0;

  string infile = argv[3];

  SolarSystem mySystem = SolarSystem(infile);

  while (t < T) {
    mySystem.advance(dt);
    t += dt;
  }

  mySystem.close();

  cout << "Finished simulation." << endl;
  return 0;
}
Esempio n. 23
0
std::vector<double> RK4::dAdt(SolarSystem &system, std::vector<double> A)
{
    double pi = 4*std::atan(1.0);
    double G = 4*pi*pi;
    int n_bodies = system.numberOfBodies();
    std::vector<double> dAdt = std::vector<double>(4*n_bodies);

    // Zeroing the vector dAdt
    for(int i=0;i<4*n_bodies;i++)
    {
        dAdt[i]=0;
    }

    // Derivating vector A
    for(int i=0;i<n_bodies;i++)
    {
        // Derivative of position is velocity
        dAdt[4*i] = A[4*i+2];
        dAdt[4*i+1] = A[4*i+3];

        double mass_i = system.bodies.at(i)->mass;
        for(int j=i+1; j<n_bodies; j++)
        {
            // Calculating gravitational force between objects
            double mass_j = system.bodies.at(j)->mass;
            double dX = A[4*j]-A[4*i];    // dX and dY "pointing" from body1 to body2
            double dY = A[4*j+1]-A[4*i+1];
            double dr = std::sqrt(dX*dX+dY*dY);

            double forcefactor = G*mass_i*mass_j/(dr*dr*dr);

            dAdt[4*i+2] += dX*forcefactor/mass_i;
            dAdt[4*i+3] += dY*forcefactor/mass_i;

            dAdt[4*j+2] -= dX*forcefactor/mass_j;
            dAdt[4*j+3] -= dY*forcefactor/mass_j;
        }
    }
return dAdt;
}
Esempio n. 24
0
void onUpdate(void) {
    solarsystem.onUpdate();
}
Esempio n. 25
0
// 用于注册GLUT的回调
void onDisplay(void) {
    solarsystem.onDisplay();
}
Esempio n. 26
0
void onKeyboard(unsigned char key, int x, int y) {
    solarsystem.onKeyboard(key, x, y);
}
Esempio n. 27
0
//Orchestrates all the objects and variables into a playable game
void GameDisplay(){
	glEnable(GL_CULL_FACE);
	glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	perspectiveStepBack = 1.0f;
	projection = perspective(25.0f, window.window_aspect, 0.01f, 1200000000.0f);
	modelview = lookAt(vec3(0.0f, perspectiveOffset, perspectiveStepBack), vec3(0.0f, 0.0f, 0.0f), vec3(0.0f, 1.0f, 0.0f));
	modelview = render(modelview);
	glLoadMatrixf(value_ptr(modelview));
	glPolygonMode(GL_FRONT_AND_BACK, window.wireframe ? GL_LINE : GL_FILL);	
	/////////////////////////////Menu Display////////////////////////////////
	if(menuOn){

		menuSelect = 1;stadiumSelect = 1;
		singlePlayer = true;

		viewPerspective = 3;
		perspectiveOffset = 0.0f;
		perspectiveStepBack = 10.0f;
		countdownOn = true;
		menuOn = false;
		transY = 0;
		gameSelect = 2;

	}
	//Countdown Display
	else if(countdownOn){
			if(first == 1){
				//alSourceStop(origSource);
				//init((ALbyte *)"./music/havingAWildTime.wav", true);
				first = 2;
			}

			countdownTime = float(glutGet(GLUT_ELAPSED_TIME)) / 1000.0f;countdownTime -= menuTime;
			countdownOn = false;
			
	}

	///////////////////////Game Display///////////////////////////
	else{
		current_timeDisplay = float(glutGet(GLUT_ELAPSED_TIME)) / 1000.0f;
		current_timeDisplay = (window.paused ? window.time_last_pause_began : current_timeDisplay) - window.total_time_paused;
		
		//Mouse movement
		mouseRotations(stadiumSelect, viewPerspective);

		//Stop the clock, user, and score calculations when caught
		if(!caught){

			modelview = endRender(modelview);
			
			mat4 scaler;
			scaler = translate(modelview, vec3(0.0f, -1.f, 0.0f));
			scaler = rotate(scaler, 90.0f, vec3(0,1,0));
			scaler = scale(scaler, vec3(1.0f, 1.0f, 1.0f));
			userTeam.drawUser = true;userTeam.drawBullet = false;
			//userTeam.Draw(projection, scaler, window.size, 0);
			userTeam.points[0].x=transX;userTeam.points[0].y=transY;userTeam.points[0].z=transZ;
			//userTeam.points[0].hRot = RotatedY;userTeam.points[0].vRot=RotatedX;

			modelview = render(modelview);

			

		}			

		//drawStadium();
		ss.Draw(projection, modelview, window.size, 0);

		
	}
	glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
	glFlush();
	
}
Esempio n. 28
0
int main(int argc, char * argv[])
{
	glewInit();
	glutInit(&argc, argv);
	glutInitWindowSize(1024, 512);
	glutInitWindowPosition(0, 0);
	glutInitDisplayMode(GLUT_RGBA | GLUT_DEPTH | GLUT_DOUBLE);

	//Initialize object's colors / values
	torus.color = vec3(1.0f, 0.1f, 0.0f);
	square.color1 = vec3(1.0, 1.0, 1.0);
	square2.color1 = vec3(0.95f, 0.1f, 0.7f);
	square2.color2 = vec3(1.0f, 1.0f, 0.0f);
	disc.color = vec3(0.1f, 0.5f, 1.0f);
	sphere.color = vec3(0.15f, 0.45f, 0.0f);
	sphere2.color = vec3(0.45f, 0.05f, 0.25f);
	cylinder.color = vec3(0.0f, 0.5f, 0.0f);
	arena.texID = 18;
	egg.texID = 20;
	star.texID = 22;
	magneton.texID = 25;
	haunter.texID = 26;
	frog.texID = 27;
	goldeen.texID = 76;
	rain2.color = vec3(0.4f, 0.4f, 1.0f);
	snow2.color = vec3(1.0f, 1.0f, 1.0f);
	fontfilename = "Pokemon.ttf";

	//Initialize the precipitation
	numParts = 300;
	partX = new float[numParts];
	partY = new float[numParts];
	partOffset = new float[numParts];
	for(int i=0; i<numParts; i++){
		partX[i] = (float)(rand() % 1200);
		partX[i] = (partX[i] - 600)/100;

		partY[i] = (float)(rand() % 1200);
		partY[i] = (partY[i] - 600)/100;
		partOffset[i] = (float)(rand() % 360 + 1);
	}
	sphere.lava = true;sphere2.lava = false; //Initialize sphere statuses

	window.window_handle = glutCreateWindow("Solar System");
	glutReshapeFunc(ReshapeFunc);
	glutCloseFunc(CloseFunc);
	
	glutMotionFunc(mouseMovement);
	glutPassiveMotionFunc(mouseMovement); //check for mouse movement
	glutKeyboardFunc(KeyboardFunc);
	glutSpecialFunc(SpecialFunc);
	glutTimerFunc(window.interval, TimerFunc, 0);
	
	glutSetOption(GLUT_ACTION_ON_WINDOW_CLOSE, GLUT_ACTION_CONTINUE_EXECUTION);
	
	//Initialize everything

	if (glewInit() != GLEW_OK)
	{
		cerr << "GLEW failed to initialize." << endl;
		return 0;
	}

	init_resources();
	glutDisplayFunc(DisplayFunc);

	if (!fbo.Initialize(glm::ivec2(512, 512), 1, true)){
		cerr << "Frame buffer failed to initialize." << endl;
		return 0;
	}

	sph1.color = vec3(1.0f, 0.85f, 0.0f);
	if (!sph1.Initialize(8,1.0f, "phong3.vert", "phong3.frag")){return 0;}
	enm.color = vec3(0.75f, 0.0f, 0.75f);
	if (!enm.Initialize(2,0.05f, "phong.vert", "phong.frag")){return 0;}
	usr.color = vec3(0.0f, 0.0f, 0.5f);
	if (!usr.Initialize(2,0.05f, "phong.vert", "phong.frag")){return 0;}
	//if (!sb.Initialize()){return 0;}
	//if (!coin.Initialize()){return 0;}
	//if (!stadium.Initialize(0)){return 0;}
	if (!skybox.Initialize(0, 5000, "basic_skybox_shader.vert", "basic_skybox_shader.frag")){return 0;}
	if (!skybox2.Initialize(1, 5025, "basic_skybox_shader.vert", "basic_skybox_shader.frag")){return 0;}
	if (!skybox3.Initialize(2, 5050, "basic_skybox_shader.vert", "basic_skybox_shader.frag")){return 0;}
	if (!skyboxUW.Initialize(3, 5075, "basic_skybox_shader.vert", "basic_skybox_shader.frag")){return 0;}


	arena.order = 1;
	
	if (!sphere.Initialize(15, 1, "sphereShader2.vert", "sphereShader2.frag")){return 0;}
	if (!sphere2.Initialize(15, 1, "sphereShader2.vert", "sphereShader2.frag")){return 0;}
	if (!rain2.Initialize(2, 0.02f, "phong.vert", "phong.frag")){return 0;}
	if (!snow2.Initialize(3, 0.02f, "phong.vert", "phong.frag")){return 0;}
	//if (!egg.Initialize(15, 1, "./textures/alienEgg.jpg", "basic_texture_shader.vert", "basic_texture_shader.frag")){return 0;}
	if (!square.Initialize(1, 3.0f, "phong.vert", "phong.frag")) {return 0;}
	if (!sq4.Initialize(1, 5.0f, "basic_texture_shader.vert", "basic_texture_shader.frag")) {return 0;}
	if (!disc.Initialize(8, 1.0f, "phong3.vert", "phong3.frag")) {return 0;}
	if (!healthBar.Initialize(2, 1.0f, 1.f, 1.f, "phong3.vert", "phong3.frag")) {return 0;}
	if (!soldier.Initialize()) {return 0;}
	if (!ss.Initialize()) {return 0;}

	userTeam.userTeam = true;
	if (!userTeam.Initialize()) {return 0;}
	if (!cpuTeam.Initialize()) {return 0;}

	glutMainLoop();
}
Esempio n. 29
0
// -----------------------------------------------------------------------------------
// Compute the satellite attitude, given the time and the satellite position SV.
// If the SolarSystem is valid, use it; otherwise use SolarPosition.
// See two versions of SatelliteAttitude() for the user interface.
// Return a 3x3 Matrix which contains, as rows, the unit (ECEF) vectors X,Y,Z in the
// body frame of the satellite, namely
//    Z = along the boresight (i.e. towards Earth center),
//    Y = perpendicular to both Z and the satellite-sun direction, and
//    X = completing the orthonormal triad. X will generally point toward the sun.
// Thus this rotation matrix R * (ECEF XYZ vector) = components in body frame, and
// R.transpose() * (sat. body. frame vector) = ECEF XYZ components.
// Also return the shadow factor = fraction of sun's area not visible to satellite.
Matrix<double> doSatAtt(const CommonTime& tt, const Position& SV,
                        const SolarSystem& SSEph, const EarthOrientation& EO,
                        double& sf)
   throw(Exception)
{
   try {
      int i;
      double d,svrange,DistSun,AngRadSun,AngRadEarth,AngSeparation;
      Position X,Y,Z,T,S,Sun;
      Matrix<double> R(3,3);

      // Z points from satellite to Earth center - along the antenna boresight
      Z = SV;
      Z.transformTo(Position::Cartesian);
      svrange = Z.mag();
      d = -1.0/Z.mag();
      Z = d * Z;                                // reverse and normalize Z

      // get the Sun's position
      if(SSEph.JPLNumber() > -1) {
         //SolarSystem& mySSEph=const_cast<SolarSystem&>(SSEph);
         Sun = const_cast<SolarSystem&>(SSEph).WGS84Position(SolarSystem::Sun,tt,EO);
      }
      else {
         double AR;
         Sun = SolarPosition(tt, AR);
      }
      DistSun = Sun.radius();

      // apparent angular radius of sun = 0.2666/distance in AU (deg)
      AngRadSun = 0.2666/(DistSun/149598.0e6);
      AngRadSun *= DEG_TO_RAD;

      // angular radius of earth at sat
      AngRadEarth = ::asin(6378137.0/svrange);

      // T points from satellite to sun
      T = Sun;                                  // vector earth to sun
      T.transformTo(Position::Cartesian);
      S = SV;
      S.transformTo(Position::Cartesian);
      T = T - S;                                // sat to sun=(E to sun)-(E to sat)
      d = 1.0/T.mag();
      T = d * T;                                // normalize T

      AngSeparation = ::acos(Z.dot(T));         // apparent angular distance, earth
                                                // to sun, as seen at satellite
      // is satellite in eclipse?
      try { sf = ShadowFactor(AngRadEarth, AngRadSun, AngSeparation); }
      catch(Exception& e) { GPSTK_RETHROW(e); }

      // Y is perpendicular to Z and T, such that ...
      Y = Z.cross(T);
      d = 1.0/Y.mag();
      Y = d * Y;                                // normalize Y

      // ... X points generally in the direction of the sun
      X = Y.cross(Z);                           // X will be unit vector
      if(X.dot(T) < 0) {                        // need to reverse X, hence Y also
         X = -1.0 * X;
         Y = -1.0 * Y;
      }

      // fill the matrix and return it
      for(i=0; i<3; i++) {
         R(0,i) = X[i];
         R(1,i) = Y[i];
         R(2,i) = Z[i];
      }

      return R;
   }
   catch(Exception& e) { GPSTK_RETHROW(e); }
   catch(exception& e) {Exception E("std except: "+string(e.what())); GPSTK_THROW(E);}
   catch(...) { Exception e("Unknown exception"); GPSTK_THROW(e); }
}
Esempio n. 30
0
void StelApp::init(QSettings* conf)
{
	confSettings = conf;

	devicePixelsPerPixel = QOpenGLContext::currentContext()->screen()->devicePixelRatio();

	setBaseFontSize(confSettings->value("gui/base_font_size", 13).toInt());
	
	core = new StelCore();
	if (saveProjW!=-1 && saveProjH!=-1)
		core->windowHasBeenResized(0, 0, saveProjW, saveProjH);

	// Initialize AFTER creation of openGL context
	textureMgr = new StelTextureMgr();
	textureMgr->init();

	networkAccessManager = new QNetworkAccessManager(this);
	// Activate http cache if Qt version >= 4.5
	QNetworkDiskCache* cache = new QNetworkDiskCache(networkAccessManager);
	QString cachePath = StelFileMgr::getCacheDir();

	qDebug() << "Cache directory is: " << QDir::toNativeSeparators(cachePath);
	cache->setCacheDirectory(cachePath);
	networkAccessManager->setCache(cache);
	connect(networkAccessManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(reportFileDownloadFinished(QNetworkReply*)));

	// Stel Object Data Base manager
	stelObjectMgr = new StelObjectMgr();
	stelObjectMgr->init();
	getModuleMgr().registerModule(stelObjectMgr);

	localeMgr = new StelLocaleMgr();
	skyCultureMgr = new StelSkyCultureMgr();
	planetLocationMgr = new StelLocationMgr();
	actionMgr = new StelActionMgr();

	localeMgr->init();

	// Init the solar system first
	SolarSystem* ssystem = new SolarSystem();
	ssystem->init();
	getModuleMgr().registerModule(ssystem);

	// Load hipparcos stars & names
	StarMgr* hip_stars = new StarMgr();
	hip_stars->init();
	getModuleMgr().registerModule(hip_stars);

	core->init();

	// Init nebulas
	NebulaMgr* nebulas = new NebulaMgr();
	nebulas->init();
	getModuleMgr().registerModule(nebulas);

	// Init milky way
	MilkyWay* milky_way = new MilkyWay();
	milky_way->init();
	getModuleMgr().registerModule(milky_way);

	// Init zodiacal light
	ZodiacalLight* zodiacal_light = new ZodiacalLight();
	zodiacal_light->init();
	getModuleMgr().registerModule(zodiacal_light);

	// Init sky image manager
	skyImageMgr = new StelSkyLayerMgr();
	skyImageMgr->init();
	getModuleMgr().registerModule(skyImageMgr);

	// Init audio manager
	audioMgr = new StelAudioMgr();

	// Init video manager
	videoMgr = new StelVideoMgr();

	// Constellations
	ConstellationMgr* asterisms = new ConstellationMgr(hip_stars);
	asterisms->init();
	getModuleMgr().registerModule(asterisms);

	// Landscape, atmosphere & cardinal points section
	LandscapeMgr* landscape = new LandscapeMgr();
	landscape->init();
	getModuleMgr().registerModule(landscape);

	GridLinesMgr* gridLines = new GridLinesMgr();
	gridLines->init();
	getModuleMgr().registerModule(gridLines);

	// Sporadic Meteors
	SporadicMeteorMgr* meteors = new SporadicMeteorMgr(10, 72);
	meteors->init();
	getModuleMgr().registerModule(meteors);

	// User labels
	LabelMgr* skyLabels = new LabelMgr();
	skyLabels->init();
	getModuleMgr().registerModule(skyLabels);

	skyCultureMgr->init();

	//Create the script manager here, maybe some modules/plugins may want to connect to it
	//It has to be initialized later after all modules have been loaded by calling initScriptMgr
#ifndef DISABLE_SCRIPTING
	scriptAPIProxy = new StelMainScriptAPIProxy(this);
	scriptMgr = new StelScriptMgr(this);
#endif

	// Initialisation of the color scheme
	emit colorSchemeChanged("color");
	setVisionModeNight(confSettings->value("viewing/flag_night").toBool());

	// Enable viewport effect at startup if he set
	setViewportEffect(confSettings->value("video/viewport_effect", "none").toString());

	// Proxy Initialisation
	setupNetworkProxy();
	updateI18n();

	// Init actions.
	actionMgr->addAction("actionShow_Night_Mode", N_("Display Options"), N_("Night mode"), this, "nightMode");

	setFlagShowDecimalDegrees(confSettings->value("gui/flag_show_decimal_degrees", false).toBool());
	setFlagOldAzimuthUsage(confSettings->value("gui/flag_use_azimuth_from_south", false).toBool());
	
	initialized = true;
}