void init_objects() { renderables = list<Renderable *>(); Planet *earth = new Planet(10, 0, 0, 0); // TODO: need to sort out the relative paths earth->setTexture("resources/earthmap1k.jpg"); renderables.push_back(earth); // Setup the player Player::player = new Player(12); renderables.push_back(Player::player); // Create the stars StarGenerator *stars = new StarGenerator(); renderables.push_back(stars); }
double DynamicBody::CalcAtmosphericForce(double dragCoeff) const { Body *body = GetFrame()->GetBody(); if (!body || !GetFrame()->IsRotFrame() || !body->IsType(Object::PLANET)) return 0.0; Planet *planet = static_cast<Planet*>(body); double dist = GetPosition().Length(); double speed = m_vel.Length(); double pressure, density; planet->GetAtmosphericState(dist, &pressure, &density); const double radius = GetClipRadius(); // bogus, preserving behaviour const double area = radius; // ^^^ yes that is as stupid as it looks return 0.5*density*speed*speed*area*dragCoeff; }
void PlanetariumEngine::update_positions(void) { QHashIterator<const sim::Body*,Planet*> i(mObjects); while (i.hasNext()) { i.next(); Planet* p = i.value(); const sim::Body* body = i.key(); double* std_pos = body->getPosition(); irr::core::vector3df position( std_pos[0] * mScale, std_pos[1] * mScale, std_pos[2] * mScale); p->getIrrlichtNode()->setPosition(position); } }
/**\brief Load a player from a file. * \param[in] filename of a player's xml saved game. * \returns pointer to new Player instance. */ Player* Player::Load( string filename ) { xmlDocPtr doc; xmlNodePtr cur; Player* newPlayer = new Player(); File xmlfile = File (filename); long filelen = xmlfile.GetLength(); char *buffer = xmlfile.Read(); doc = xmlParseMemory( buffer, static_cast<int>(filelen) ); cur = xmlDocGetRootElement( doc ); newPlayer->FromXMLNode( doc, cur ); // We check the planet location at loadtime in case planet moved or lastPlanet changed. // This happens with --random-universe. TODO: Does this matter? random-universe was removed. Planet* p = Menu::GetCurrentScenario()->GetPlanets()->GetPlanet( newPlayer->lastPlanet ); if( p != NULL ) { newPlayer->SetWorldPosition( p->GetWorldPosition() ); } else { LogMsg(INFO, "There is no planet named: '%s'.", newPlayer->lastPlanet.c_str() ); } newPlayer->RemoveLuaControlFunc(); // We can't start the game with bad player Information assert( newPlayer->GetModelName() != "" ); assert( newPlayer->GetEngineName() != "" ); // Tell Lua to initialize these escorts. for(list<Player::HiredEscort*>::iterator iter_escort = newPlayer->hiredEscorts.begin(); iter_escort != newPlayer->hiredEscorts.end(); iter_escort++) { (*iter_escort)->Lua_Initialize( newPlayer->GetID(), newPlayer->GetWorldPosition() ); } // Remember this Player newPlayer->lastLoadTime = time(NULL); LogMsg(INFO, "Successfully loaded the player: '%s'.", newPlayer->GetName().c_str() ); LogMsg(INFO, "Loaded Player '%s' with Model='%s' Engine='%s' Credits = %d at (%.0f,%.0f).", newPlayer->GetName().c_str(), newPlayer->GetModel()->GetName().c_str(), newPlayer->GetEngine()->GetName().c_str(), newPlayer->GetCredits(), newPlayer->GetWorldPosition().GetX(), newPlayer->GetWorldPosition().GetY() ); return newPlayer; }
bool GameEngine::CanMoveFrom(Planet& planeta, uint16 gracz) const { uint16 okup=planeta.RetOkupant(); if(okup) { if(okup==gracz) return true; return false; } else { if(planeta.RetGracz()==gracz) return true; return false; }; };
Result Bombard::inputFrame(Frame * f, unsigned int playerid) { Result r = Order::inputFrame(f, playerid); if(!r) return r; ObjectManager *om = Game::getGame()->getObjectManager(); IGObject *planetObj = om->getObject(planet->getObjectId()); Planet *planetData = dynamic_cast<Planet*>(planetObj->getObjectBehaviour()); if(!planetData) planet->setObjectId(0); else if(planetData->getOwner() == playerid) planet->setObjectId(0); return Success(); }
void ChunkManager::update() { if (!planetList.empty()) { timeNow = Planet::getTimer().getMilliseconds(); std::list<Planet*>::iterator i; for (i = planetList.begin(); i != planetList.end(); ++i) { Planet *planet = *i; expirationTime = planet->getChunkLoader()->getExpirationTime(); for (Ogre::uint32 o = 0; o < 6; ++o) { updateNode(planet->getCubeFace(o)); } } } }
void DynamicBody::CalcExternalForce() { // gravity if (!GetFrame()) return; // no external force if not in a frame Body *body = GetFrame()->GetBody(); if (body && !body->IsType(Object::SPACESTATION)) { // they ought to have mass though... vector3d b1b2 = GetPosition(); double m1m2 = GetMass() * body->GetMass(); double invrsqr = 1.0 / b1b2.LengthSqr(); double force = G*m1m2 * invrsqr; m_externalForce = -b1b2 * sqrt(invrsqr) * force; } else m_externalForce = vector3d(0.0); m_gravityForce = m_externalForce; // atmospheric drag if (body && GetFrame()->IsRotFrame() && body->IsType(Object::PLANET)) { Planet *planet = static_cast<Planet*>(body); double dist = GetPosition().Length(); double speed = m_vel.Length(); double pressure, density; planet->GetAtmosphericState(dist, &pressure, &density); const double radius = GetClipRadius(); // bogus, preserving behaviour const double AREA = radius; // ^^^ yes that is as stupid as it looks const double DRAG_COEFF = 0.1; // 'smooth sphere' vector3d dragDir = -m_vel.NormalizedSafe(); vector3d fDrag = 0.5*density*speed*speed*AREA*DRAG_COEFF*dragDir; // make this a bit less daft at high time accel // only allow atmosForce to increase by .1g per frame vector3d f1g = m_atmosForce + dragDir * GetMass(); if (fDrag.LengthSqr() > f1g.LengthSqr()) m_atmosForce = f1g; else m_atmosForce = fDrag; m_externalForce += m_atmosForce; } else m_atmosForce = vector3d(0.0); // centrifugal and coriolis forces for rotating frames if (GetFrame()->IsRotFrame()) { vector3d angRot(0, GetFrame()->GetAngSpeed(), 0); m_externalForce -= m_mass * angRot.Cross(angRot.Cross(GetPosition())); // centrifugal m_externalForce -= 2 * m_mass * angRot.Cross(GetVelocity()); // coriolis } }
void Scene::createScene(TextureManager* texture, ID3D11Device* pd3dDevice, ID3D11DeviceContext* context, Shader* shader){ std::wstring txtName = L"ships/F5S4.png"; std::wstring playerShip = L"ships/F5S2.png"; std::wstring planetTexture = L"planets/spr_planet01.png"; texture->createTexture(&txtName); texture->createTexture(&playerShip); texture->createTexture(&planetTexture); int count = 0; int h = 6; for (int i = 0; i <= trisH; i++){ float startX = -h * (i / 2.0); float startY = i * h; for (int b = 0; b < i; b++){ ships[count++] = new Ship(txtName.c_str(), txtName.c_str(), &Vec3{ startX + b*h, startY, 0 }); } } ships[shipAmount - 1] = new Ship(txtName.c_str(), txtName.c_str(), &Vec3{0,-2,0 }); for (int i = 0; i < shipAmount; i++){ ships[i]->create(pd3dDevice,context,shader); ships[i]->setTexture(txtName); ships[i]->mulScale(1, 1, 1); registerObject(ships[i]); } getPlayerShip()->setTexture(playerShip); Planet* p = new Planet(&Vec3(100,0,0)); p->create(pd3dDevice, context, shader); p->setTexture(planetTexture); p->mulScale(35, 35, 1); registerObject(p); Planet* p2 = new Planet(&Vec3(-100, 0, 0)); p2->create(pd3dDevice, context, shader); p2->setTexture(planetTexture); p2->mulScale(35, 35, 1); registerObject(p2); Planet* p3 = new Planet(&Vec3(0, 100, 0)); p3->create(pd3dDevice, context, shader); p3->setTexture(planetTexture); p3->mulScale(15, 15, 1); //registerObject(p3); }
void SolarSystemCreator::createWorlds() { double currentDistance; _star->numDesert(0); _star->numGasGiant(0); double prevSatDistance = 0.0; //double prevDistance = 0.0; const double MIN_PLANET_DISTANCE_GG = 4000000.0; const double MAX_OUTER_PLANET = 100.0; _star->calcStarValue(); for (int h = 0; h < _orbits; h++) { bool advanceNextPlanet = true; do { Planet px; px.setStar(_star.data()); if (h == 0) { double dModifier = 0.1; if (_star->starType() == NSStar::stM) dModifier *= .33; if (_star->starType() == NSStar::stK) dModifier *= .66; if (_star->starType() == NSStar::stF) dModifier *= 1.25; currentDistance = dModifier + SSGX::floatRand() * dModifier; } else { prevSatDistance = currentDistance; auto minDistance = currentDistance + (prevSatDistance * 50.0 / 150000000.0); auto newDistance = (currentDistance * (1.05+ (double)(rand() % 900)/1000.0)) - currentDistance; if (minDistance > newDistance) currentDistance += minDistance; else currentDistance += newDistance; } int chance = SSGX::d10(); if (chance < 8 && currentDistance < MAX_OUTER_PLANET) { makePlanet(advanceNextPlanet, MIN_PLANET_DISTANCE_GG, currentDistance, prevSatDistance, px); } } while (!advanceNextPlanet); } _star->calcStarValue(); }
Planet::Planet(const Planet& p) : ships_count(p.ships_count), _planet_id(p._planet_id), _growth_rate(p._growth_rate), _coordinate(p.coordinate()), _ownerID(p._ownerID) { }
// intersection of view direction with globe in geodetic Geodetic3D* _getGeodeticCenterOfView() const { if (_dirtyFlags._geodeticCenterOfViewDirty) { _dirtyFlags._geodeticCenterOfViewDirty = false; delete _geodeticCenterOfView; _geodeticCenterOfView = new Geodetic3D(_planet->toGeodetic3D(getXYZCenterOfView())); } return _geodeticCenterOfView; }
map<uint32_t, pair<string, uint32_t> > Colonize::generateListOptions() { map<uint32_t, pair<string,uint32_t> > options; Game* game = Game::getGame(); ObjectManager* om = game->getObjectManager(); IGObject::Ptr selectedObj = game->getObjectManager()->getObject( game->getOrderManager()->getOrderQueue(orderqueueid)->getObjectId()); Planet* planet = dynamic_cast<Planet*>(selectedObj->getObjectBehaviour()); assert(planet); om->doneWithObject(selectedObj->getID()); set<uint32_t> allObjs = om->getAllIds(); uint32_t availibleUnits = planet->getResource("Army").first + planet->getResource("Army").second - 1; /* This for loop will iterate over every adjacent planet. This is where the majority of the work occurs, and we populate our list. You see here we select an item of the map, in my case (*i)->getID(), and for that item we create a pair. If its a little hard to read, here is what I am doing: options[#] = pair<string,uint32_t>( "title", max# ); For my pair I set the title as the adjacent planet to move to, and set the max to availible units. */ for(set<uint32_t>::iterator i = allObjs.begin(); i != allObjs.end(); i++) { IGObject::Ptr currObj = om->getObject((*i)); Planet* owned = dynamic_cast<Planet*>(currObj->getObjectBehaviour()); if ( owned != NULL && owned->getOwner() == 0) { options[owned->getID()] = pair<string,uint32_t>( owned->getName(), availibleUnits ); } } return options; }
void TestGame::Init() { Entity *camera = new Entity( Vector3f( 0, 5, 15 ) ); camera->AddComponent( new FreeLookFreeMoveComponent() ); SetCamera( camera ); Planet *planet = new Planet( 12310, 4, 10.0f, 30 ); Entity *entity = new Entity(); RenderComponent* render = new RenderComponent( planet->CreateMesh() ); render->SetShaderType( ShaderType::SHADER_COLORIZED ); entity->AddComponent( render ); entity->AddComponent( new PlanetColorComponent( planet ) ); AddToScene( entity ); // Entity* cube = new Entity(); // cube->AddComponent( new RenderComponent( "cube.obj", "test.png" ) ); // AddToScene( cube ); }
Planet* UnitFactory::createPlanet( QVector x, QVector y, float vely, const Vector &rotvel, float pos, float gravity, float radius, const std::string &filename, const std::string &technique, const std::string &unitname, BLENDFUNC sr, BLENDFUNC ds, const vector< string > &dest, const QVector &orbitcent, Unit *parent, const GFXMaterial &ourmat, const std::vector< GFXLightLocal > &ligh, int faction, string fullname, bool inside_out, ObjSerial netcreate ) { _Universe->netLock( true ); Planet *p = new Planet( x, y, vely, rotvel, pos, gravity, radius, filename, technique, unitname, dest, orbitcent, parent, faction, fullname, inside_out, ligh.size() ); _Universe->netLock( false ); if (netcreate) p->SetSerial( netcreate ); /* * // False: Only allow creation through system files? Doesn't make sense to be able to dynamically generate these. * // Could cause inconsistencies with new clients that just read system files. * if ( false && !_Universe->netLocked()) { * NetBuffer netbuf; * // Send a packet to clients in order to make them create this unit * * addPlanetBuffer( netbuf, x, y, vely, rotvel, pos, gravity, radius, filename, sr, ds, dest, orbitcent, parent, ourmat, ligh, faction, fullname, inside_out, netcreate); * endBuffer( netbuf ); * VSServer->broadcast( netbuf, 0, _Universe->activeStarSystem()->GetZone(), CMD_ENTERCLIENT, true); * } * VSServer->invalidateSnapshot(); */ return p; }
// round从0算起 void StageEndlessLayer::initCatPlanetsWithRound(int round) { int countForSide = 0; if(round < 2) countForSide = 2; else countForSide = 3; for(int i = 0; i <countForSide; i++) { int fightUnit = 10; CCPoint posi = getRandomPlanetPosition(); if(posi.x > 0 && posi.y > 0) { Planet* cat = makePlanet(kForceSideCat, posi, fightUnit, 0); m_pCatPlanetArray->addObject(cat); } } // 以9为一个循环数 int levelSum = (round % 9)* 1.5; levelSum -=2; if(levelSum < 0) levelSum = 0; if(levelSum > 5) levelSum = 5; while(levelSum > 0) { CCObject* pOb = NULL; CCARRAY_FOREACH(m_pCatPlanetArray, pOb) { Planet* pPlanet = (Planet*) pOb; if(!pPlanet->isDirty()) { if(levelSum >0) { pPlanet->levelUp(); --levelSum; } } } }
bool Planet::IsGoal( Planet &nodeGoal ) { if( this->planetID() == nodeGoal.planetID() ) { return true; } return false; }
bool Bombard::doOrder(IGObject *fleet) { Game *game = Game::getGame(); ObjectManager *om = game->getObjectManager(); ObjectTypeManager *odm = game->getObjectTypeManager(); Random *rand = game->getRandom(); IGObject *planetObj = om->getObject(planet->getObjectId()); if(planetObj->getType() != odm->getObjectTypeByName("Planet")) { Logger::getLogger()->debug("Player tried to bombard something illogical"); return true; } Fleet *fleetData = dynamic_cast<Fleet*>(fleet->getObjectBehaviour()); Planet *planetData = dynamic_cast<Planet*>(planetObj->getObjectBehaviour()); char planetShipTech = PlayerInfo::getPlayerInfo(planetData->getOwner()).getShipTechLevel(); double attack = fleetData->getAttack(); planetData->removeResource("Industry", static_cast<uint32_t>(attack * INDUSTRY_DMG * (1+rand->getInRange(-2,2)/100.) )); planetData->removeResource("Social Environment", static_cast<uint32_t>(attack * SOCIAL_DMG * (1+rand->getInRange(-2,2)/100.) )); planetData->removeResource("Planetary Environment", static_cast<uint32_t>(attack * PLANETARY_DMG * (1+rand->getInRange(-2,2)/100.) )); planetData->removeResource(string("PDB") + planetShipTech, static_cast<uint32_t>(attack * PDB_DMG / 10. * (1+rand->getInRange(-2,2)/100.) )); PlayerInfo::getPlayerInfo(fleetData->getOwner()).addVictoryPoints(VICTORY_POINTS); // PDBs counter-attack at: PDB level * 6 * numPDBs fleetData->takeDamage( (planetShipTech - '0') * 6 * planetData->getResource(string("PDB") + planetShipTech).first); Message *msg = new Message(); msg->setSubject("Bombard complete"); string body = "Fleet \"" + fleet->getName() + "\" bombarded " + planetObj->getName(); msg->setBody(PlayerInfo::appAllVictoryPoints(body)); msg->addReference(rst_Action_Order, rsorav_Completion); msg->addReference(rst_Object, fleet->getID()); msg->addReference(rst_Object, planetObj->getID()); game->getPlayerManager()->getPlayer(fleetData->getOwner())->postToBoard(msg); game->getPlayerManager()->getPlayer(planetData->getOwner())->postToBoard(msg); return true; }
virtual bool objectEnd(const std::string &name) { if(otype.empty()) return false; switch(otype.back()) { case OT_RACES: new Genus(color, grow, 1.0f / strength, linkFactor, 4.0f, 0.2f, 0.85f, 0.3f, PI/6.0f, 0.3f, 0.02f, 1.5f, 0.2f, PI/6.0f, 0.3f); return true; case OT_PLANET: { Planet *p = new Planet(position, radius, rich); world.addPlanet(p); if(!trees.empty()) { float sizeSum = 0; for(std::vector<TreeInfo>::iterator it = trees.begin(); it!=trees.end(); ++it) sizeSum += it->size; if(sizeSum > 1.0) { float factor = 1.0f / sizeSum; for(std::vector<TreeInfo>::iterator it = trees.begin(); it!=trees.end(); ++it) it->size *= factor; } for(std::vector<TreeInfo>::iterator it = trees.begin(); it!=trees.end(); ++it) if(it->race < (int)genuses.size()) Tree::build(genuses[it->race], p, it->size*p->getMaxLength(), it->dir); } } return true; case OT_BLACK_HOLE: { BlackHole *b = new BlackHole(position, radius); } return true; case OT_TREES: trees.push_back(TreeInfo(race, size, dir)); return true; } return false; }
void page_update_planet() { SDL_Rect srcr = {0, 0, 64, 64}; SDL_Rect destr = {0, 0, 64, 64}; Planet *plan = (Planet*)cur_object; if(lasttick != -1) { for(int sctr=0; sctr < plan->num_satellites; ++sctr) { Satellite *sat = plan->satellites[sctr]; srcr.x = sat->XPos(lasttick) - 32; srcr.y = sat->YPos(lasttick) - 32; destr.x = sat->XPos(lasttick) - 32; destr.y = sat->YPos(lasttick) - 32; SDL_FillRect(screen, &destr, black); SDL_BlitSurface(planet[plan->Type()], &srcr, screen, &destr); update(&destr); } } for(int sctr=0; sctr < plan->num_satellites; ++sctr) { Satellite *sat = plan->satellites[sctr]; if(!(sat->InFront(cur_game->tick))) { srcr.x = sat->XPos(cur_game->tick) - 32; srcr.y = sat->YPos(cur_game->tick) - 32; destr.x = sat->XPos(cur_game->tick) - 32; destr.y = sat->YPos(cur_game->tick) - 32; SDL_BlitSurface(satellite[sat->Type()], NULL, screen, &destr); SDL_BlitSurface(planet[plan->Type()], &srcr, screen, &destr); update(&destr); } } for(int sctr=0; sctr < plan->num_satellites; ++sctr) { Satellite *sat = plan->satellites[sctr]; if(sat->InFront(cur_game->tick)) { srcr.x = sat->XPos(cur_game->tick) - 32; srcr.y = sat->YPos(cur_game->tick) - 32; destr.x = sat->XPos(cur_game->tick) - 32; destr.y = sat->YPos(cur_game->tick) - 32; SDL_BlitSurface(satellite[sat->Type()], NULL, screen, &destr); update(&destr); } } lasttick = cur_game->tick; }
Planet* UnitFactory::createPlanet( QVector x, QVector y, float vely, const Vector & rotvel, float pos, float gravity, float radius, const char * filename, BLENDFUNC sr, BLENDFUNC ds, const vector<string> &dest, const QVector &orbitcent, Unit * parent, const GFXMaterial & ourmat, const std::vector <GFXLightLocal> & ligh, int faction, string fullname , bool inside_out, ObjSerial netcreate) { Planet * p = new GamePlanet( x, y, vely, rotvel, pos, gravity, radius, filename, sr,ds, dest, orbitcent, parent, ourmat, ligh, faction, fullname , inside_out); if( netcreate) { KillDuplicateUnits( netcreate); p->SetSerial( netcreate); } return p; }
bool deathCheck() { if (liveCount >= 2000) { destroy(); return false; } if (distance(getPosition(position),planet1->getAt()) <= planet1->boundingRadius) { destroy(); return false; } if (distance(getPosition(position),planet2->getAt()) <= planet2->boundingRadius) { destroy(); return false; } if (distance(getPosition(position),sun->getAt()) <= sun->boundingRadius) { destroy(); return false; } if (distance(getPosition(position),target1->getAt()) <= target1->boundingRadius) { destroy(); return false; } if (distance(getPosition(position),target2->getAt()) <= target2->boundingRadius) { destroy(); return false; } }
std::string PlanetWarsGame::toString(Player* pov) const { std::stringstream gameState; const int numPlanets = static_cast<int>(m_planets.size()); //Write the planets. for (int i = 0; i < numPlanets; ++i) { Planet* planet = m_planets[i]; gameState << "P " << planet->getX() << " " << planet->getY() << " " << pov->povId(planet->getOwner()) << " " << planet->getNumShips() << " " << planet->getGrowthRate() << std::endl; } //Write the fleets. for (FleetList::const_iterator it = m_fleets.begin(); it != m_fleets.end(); ++it) { Fleet* fleet = (*it); gameState << "F " << pov->povId(fleet->getOwner()) << " " << fleet->getNumShips() << " " << fleet->getSource()->getId() << " " << fleet->getDestination()->getId() << " " << fleet->getTotalTripLength() << " " << fleet->getTurnsRemaining() << std::endl; } gameState << "go" << std::endl; return gameState.str(); }
void update(void) { GLfloat xPositionT = 0 + sin(orbitTimer * rotateModifier) * radius; GLfloat zPositionT = 0 + cos(orbitTimer * rotateModifier) * radius; planet.setPosition(xPositionT ,planet.yPosition , zPositionT); upPole.setPosition(xPositionT , upPole.yPosition , zPositionT); GLfloat angle = atan2(zPositionT , xPositionT); angle = -angle * 180.0f / (GLfloat)M_PI; angle+= 90.0f; outPole.setAngle(0, angle, 0); }
void System::LoadObject(const DataNode &node, Set<Planet> &planets, int parent) { int index = objects.size(); objects.push_back(StellarObject()); StellarObject &object = objects.back(); object.parent = parent; bool isAdded = (node.Token(0) == "add"); if(node.Size() >= 2 + isAdded) { Planet *planet = planets.Get(node.Token(1 + isAdded)); object.planet = planet; planet->SetSystem(this); } for(const DataNode &child : node) { if(child.Token(0) == "sprite" && child.Size() >= 2) { object.LoadSprite(child); object.isStar = !child.Token(1).compare(0, 5, "star/"); if(!object.isStar) { object.isStation = !child.Token(1).compare(0, 14, "planet/station"); object.isMoon = (!object.isStation && parent >= 0 && !objects[parent].IsStar()); } } else if(child.Token(0) == "distance" && child.Size() >= 2) object.distance = child.Value(1); else if(child.Token(0) == "period" && child.Size() >= 2) object.speed = 360. / child.Value(1); else if(child.Token(0) == "offset" && child.Size() >= 2) object.offset = child.Value(1); else if(child.Token(0) == "object") LoadObject(child, planets, index); else child.PrintTrace("Skipping unrecognized attribute:"); } }
void ObjectViewerView::OnChangeGeoSphereStyle() { SBody sbody; const fixed volatileGas = fixed(65536.0*atof(m_sbodyVolatileGas->GetText().c_str()), 65536); const fixed volatileLiquid = fixed(65536.0*atof(m_sbodyVolatileLiquid->GetText().c_str()), 65536); const fixed volatileIces = fixed(65536.0*atof(m_sbodyVolatileIces->GetText().c_str()), 65536); const fixed life = fixed(65536.0*atof(m_sbodyLife->GetText().c_str()), 65536); const fixed volcanicity = fixed(65536.0*atof(m_sbodyVolcanicity->GetText().c_str()), 65536); const fixed metallicity = fixed(65536.0*atof(m_sbodyMetallicity->GetText().c_str()), 65536); const fixed mass = fixed(65536.0*atof(m_sbodyMass->GetText().c_str()), 65536); const fixed radius = fixed(65536.0*atof(m_sbodyRadius->GetText().c_str()), 65536); sbody.parent = 0; sbody.name = "Test"; /* These should be the only SBody attributes GeoSphereStyle uses */ sbody.type = SBody::TYPE_PLANET_TERRESTRIAL; sbody.seed = atoi(m_sbodySeed->GetText().c_str()); sbody.radius = radius; sbody.mass = mass; sbody.averageTemp = 273; sbody.m_metallicity = metallicity; sbody.m_volatileGas = volatileGas; sbody.m_volatileLiquid = volatileLiquid; sbody.m_volatileIces = volatileIces; sbody.m_volcanicity = volcanicity; sbody.m_life = life; sbody.heightMapFilename = 0; Body *body = Pi::player->GetNavTarget(); if (body->IsType(Object::PLANET)) { Planet *planet = static_cast<Planet*>(body); GeoSphere *gs = planet->GetGeoSphere(); gs->m_style = GeoSphereStyle(&sbody); // force rebuild gs->OnChangeDetailLevel(); } }
/** * Affects a movable object with a planet's gravity, in proportion to the object's * mass. */ void GravityStrategy::affect(MovableObject& mwo, const Planet& swo) { // Vector from planet to object. Vector2d mwo_to_swo = swo.getPosition() - mwo.getPosition(); // Distance between centers of object and planet. float distance = mwo_to_swo.getLength(); // Unit vector pointing at planet from MovableObject. Vector2d planet_to_obj = mwo_to_swo/distance; // Note to Jesper: Should it be this way? // The gravity strategy seems to mess up when mass is 0... if (mwo.getMass() == 0) { return; } if(distance < 15.0) return; // std::cout << "Planet to obj: " << planet_to_obj.getX() << " " << planet_to_obj.getY() << std::endl; float G = 10.0f; // Value of force. float force = (G * mwo.getMass() * swo.getMass()) / (distance*distance); // Complete force with direction. Vector2d forcedir = planet_to_obj * force; // Amount of acceleration. Vector2d acc = forcedir / mwo.getMass(); // Accelerate movableobject. Vector2d mov(mwo.getMovement()); mov = mov + acc; mwo.setMovement(mov); }
bool Planet::IsSameState( Planet &rhs ) { // same state in a maze search is simply when (x,y) are the same if(this->planetID() == rhs.planetID()) { return true; } else { return false; } }
//System cannot be destroyed, occupied, or colonized in order to be able to be colonized. //It also must be inhabitable for the colony type. bool StarSystem::canBeColonized(bool mining) { ObjectManager* obm = Game::getGame()->getObjectManager(); ObjectTypeManager* obtm = Game::getGame()->getObjectTypeManager(); if(isDestroyed()) { Logger::getLogger()->debug("StarSystem->canBeColonized: System is destroyed"); return false; } //Grab the children and see if the system is occupied set<uint32_t> children = obj->getContainedObjects(); uint32_t pid; bool isOccupied = false; for(set<uint32_t>::iterator i = children.begin(); i != children.end(); i++) { if(obm->getObject(*i)->getType() == obtm->getObjectTypeByName("Planet")) { pid = *i; } else if (obm->getObject(*i)->getType() == obtm->getObjectTypeByName("Fleet")) { isOccupied = true; } } if(isOccupied) { Logger::getLogger()->debug("StarSystem->canBeColonized: System is occupied"); return false; } //Check to see if the system has already been colonized Planet* planet = (Planet*)(obm->getObject(pid)->getObjectBehaviour()); if(planet->getResource(4) > 0) { Logger::getLogger()->debug("StarSystem->canBeColonized: System has been colonized by merchants."); return false; } else if(planet->getResource(5) > 0) { Logger::getLogger()->debug("StarSystem->canBeColonized: System has been colonized by scientists."); return false; } else if(planet->getResource(6) > 0) { Logger::getLogger()->debug("StarSystem->canBeColonized: System has been colonized by settlers."); return false; } else if(planet->getResource(7) > 0) { Logger::getLogger()->debug("StarSystem->canBeColonized: System has been colonized by mining robots."); return false; } //Check to make sure the system is inhabitable by the fleet if(mining && planet->getResource(1) < 1) { Logger::getLogger()->debug("StarSystem->canBeColonized: System is inhabitable and cannot be colonized by mining robots"); return false; } else if(!mining && planet->getResource(1) > 0) { Logger::getLogger()->debug("StarSystem->canBeColonized: System is Uninhabitable and can ONLY be colonized by mining robots"); return false; } return true; }
/**\brief Get a planet by name or id */ int Planets_Lua::Get(lua_State* L){ int n = lua_gettop(L); // Number of arguments if( n!=1 ){ return luaL_error(L, "Got %d arguments expected 1 (id or name)", n); } Planet* p = NULL; if(lua_isstring(L,1)) { string name = (string)luaL_checkstring(L,1); p = (Planet*)Planets::Instance()->GetPlanet(name); if (p==NULL){ return luaL_error(L, "There is no planet by the name of '%s'", name.c_str()); } } else if(lua_isnumber(L,1)) { int id = (int)luaL_checkinteger(L,1); p = (Planet*)SpriteManager::Instance()->GetSpriteByID(id); if (p==NULL || p->GetDrawOrder() != DRAW_ORDER_PLANET){ return luaL_error(L, "There is no planet with ID %d", id); } } else { return luaL_error(L, "Cannot get planet with these arguments. Expected id or name."); } Lua::pushSprite(L,p); return 1; }