// reset simulation
bool TestDisplay::onResetKey()
{
   if ( getSimulation() != nullptr ) {
      getSimulation()->event(RESET_EVENT);
   }
   return true;
}
Esempio n. 2
0
// reset simulation
bool InstrumentPanel::onResetKey()
{
   if ( getSimulation() != nullptr ) {
      getSimulation()->event(RESET_EVENT);
   }
   return true;
}
Esempio n. 3
0
// freeze simulation
bool InstrumentPanel::onFreezeKey()
{
   if ( getSimulation() != nullptr ) {
      oe::base::Boolean newFrz( !getSimulation()->isFrozen() );
      getSimulation()->event(FREEZE_EVENT, &newFrz);
   }
   return true;
}
StatisticsCollector::StatisticsCollector() {
//    arrivalPercentage = new cLongHistogram();
//    arrivalTime = new cDoubleHistogram();

    listener = new StatisticsListener(&arrivalPercentage,&arrivalTime);
    getSimulation()->getSystemModule()->subscribe("arrival",listener);
    getSimulation()->getSystemModule()->subscribe("arrivalTime", listener);
}
Esempio n. 5
0
//------------------------------------------------------------------------------
// processFirePDU() callback -- 
//------------------------------------------------------------------------------
void NetIO::processFirePDU(const FirePDU* const pdu)
{
    // Get the Firing Player's ID
    unsigned short fPlayerId = pdu->firingEntityID.ID;
    unsigned short fSiteId = pdu->firingEntityID.simulationID.siteIdentification;
    unsigned short fApplicationId = pdu->firingEntityID.simulationID.applicationIdentification;
    
    //std::cout << "NetIO::processFirePDU() fired";
    //std::cout << "(" << pdu->firingEntityID.ID;
    //std::cout << "," << pdu->firingEntityID.simulationID.applicationIdentification ;
    //std::cout << "," << pdu->firingEntityID.simulationID.siteIdentification;
    //std::cout << ")" << std::endl;
    
    // Ignore our own PDUs
    if (fSiteId == getSiteID() && fApplicationId == getApplicationID()) return;
    
    //pdu->dumpData();
    
    // Get the Munition Player's ID
    unsigned short mPlayerId = pdu->munitionID.ID;
    unsigned short mSiteId = pdu->munitionID.simulationID.siteIdentification;
    unsigned short mApplicationId = pdu->munitionID.simulationID.applicationIdentification;
    
    // Get the Target Player's ID
    unsigned short tPlayerId = pdu->targetEntityID.ID;
    unsigned short tSiteId = pdu->targetEntityID.simulationID.siteIdentification;
    unsigned short tApplicationId = pdu->targetEntityID.simulationID.applicationIdentification;
    
    // ---
    // 1) Find the target (local) player
    // ---
    Simulation::Player* tPlayer = 0;
    if (tSiteId == getSiteID() && tApplicationId == getApplicationID()) {
        // Must be local
        SPtr<Basic::PairStream> players( getSimulation()->getPlayers() );
        tPlayer = getSimulation()->findPlayer(tPlayerId);
    }
    //std::cout << "Net Fire(2) tPlayer = " << tPlayer << std::endl;
    
    // ---
    // 2) Find the firing player and munitions (networked) IPlayers
    // ---
    Simulation::Nib* fNib = 0;
    Simulation::Nib* mNib = 0;
    if (fSiteId != getSiteID() || fApplicationId != getApplicationID()) {
        // Must be networked players
        fNib = findDisNib(fPlayerId, fSiteId, fApplicationId, INPUT_NIB);
        mNib = findDisNib(mPlayerId, mSiteId, mApplicationId, INPUT_NIB);
    }
    //std::cout << "Net Fire(3) fNib = " << fNib << ", mNib = " << mNib << std::endl;

    // --- Nothing really needs to be done.
}
Esempio n. 6
0
/**-------------------------------------------------------------------------------
    SensorDecoratorVector

    @brief
    @param color
    @return
---------------------------------------------------------------------------------*/
SensorDecoratorVector::SensorDecoratorVector(Sensor* sensor, const Ogre::ColourValue& color, bool persistent)
	: SensorDecorator(sensor), ManualObject(sensor->getSensorName())
{
	Ogre::SceneNode* myManualObjectNode = getSimulation()->getScene()->getSceneManager().getRootSceneNode()->createChildSceneNode(mName + "_node");

	Ogre::MaterialPtr myManualObjectMaterial = Ogre::MaterialManager::getSingleton().create(mName + "Material", OGRE_DEBUG_GROUP);
	myManualObjectMaterial->setReceiveShadows(false);
	myManualObjectMaterial->getTechnique(0)->setLightingEnabled(true);
	myManualObjectMaterial->getTechnique(0)->getPass(0)->setDiffuse(color);
	myManualObjectMaterial->getTechnique(0)->getPass(0)->setAmbient(color);
	myManualObjectMaterial->getTechnique(0)->getPass(0)->setSelfIllumination(color);

	myManualObjectNode->attachObject(this);

	mPersistent = persistent;
	mVisible = false;

	Ogre::Vector3 zero(0,0,0);
	begin(mName + "Material", Ogre::RenderOperation::OT_LINE_LIST);
	position(zero);
	position(zero);
	position(zero);
	position(zero);
	position(zero);
	position(zero);
	position(zero);
	position(zero);
	position(zero);
	position(zero);
	end();
}
//------------------------------------------------------------------------------
// stepOwnshipPlayer() -- Step to the next local player
//------------------------------------------------------------------------------
void SimStation::stepOwnshipPlayer()
{
   Basic::PairStream* pl = getSimulation()->getPlayers();
   if (pl != nullptr) {

      Simulation::Player* f = nullptr;
      Simulation::Player* n = nullptr;
      bool found = false;

      // Find the next player
      Basic::List::Item* item = pl->getFirstItem();
      while (item != nullptr) {
         Basic::Pair* pair = static_cast<Basic::Pair*>(item->getValue());
         if (pair != nullptr) {
            Simulation::Player* ip = static_cast<Simulation::Player*>(pair->object());
            if ( ip->isMode(Simulation::Player::ACTIVE) &&
               ip->isLocalPlayer() &&
               ip->isClassType(typeid(Simulation::AirVehicle))
               ) {
                  if (f == nullptr) { f = ip; }  // Remember the first
                  if (found)        { n = ip; ; break; }
                  if (ip == getOwnship()) found = true;
            }
         }
         item = item->getNext();
      }
      if (found && n == nullptr) n = f;
      if (n != nullptr) setOwnshipPlayer(n);

      pl->unref();
    }
}
Esempio n. 8
0
//------------------------------------------------------------------------------
// shutdownNotification() -- We're shutting down
//------------------------------------------------------------------------------
bool Station::shutdownNotification()
{
   // Tell the interoperability networks that we're shutting down
   if (networks != 0) {
      Basic::List::Item* item = networks->getFirstItem();
      while (item != 0) {
         Basic::Pair* pair = (Basic::Pair*)(item->getValue());
         Basic::Component* p = dynamic_cast<Basic::Component*>(pair->object());
         p->event(SHUTDOWN_EVENT);
         item = item->getNext();
      }
   }
   setSlotNetworks(0);

   // Tell the I/O devices that we're shutting down
   if (ioHandlers != 0) {
      Basic::List::Item* item = ioHandlers->getFirstItem();
      while (item != 0) {
         Basic::Pair* pair = (Basic::Pair*)(item->getValue());
         Basic::Component* p = dynamic_cast<Basic::Component*>(pair->object());
         p->event(SHUTDOWN_EVENT);
         item = item->getNext();
      }
   }
   setSlotIoHandler((Basic::PairStream*)0);

   // Tell our simulation to shut down
   Simulation* s = getSimulation();
   if (s != 0) {
      s->event(SHUTDOWN_EVENT);
   }
   setOwnshipPlayer(0);

   // Inform our OTW interfaces
   if (otw != 0) {
      Basic::List::Item* item = otw ->getFirstItem();
      while (item != 0) {
         Basic::Pair* pair = (Basic::Pair*)(item->getValue());
         Basic::Component* p = dynamic_cast<Basic::Component*>(pair->object());
         p->event(SHUTDOWN_EVENT);
         item = item->getNext();
      }
   }
   setSlotOutTheWindow((Basic::PairStream*)0);

   // Zero (unref) our thread objects (of any).  The thread's functions have ref()'d
   // these objects, so they won't be deleted until the threads terminate, which they
   // will based on our BaseClass::isShutdown() function.  But at least we won't
   // mistakenly think that they're still around.
   tcThread = 0;
   netThread = 0;
   bgThread = 0;

   // remove the reset timer
   setSlotStartupResetTime(0);

   return BaseClass::shutdownNotification();
}
void TPZNetworkSquareMidimew :: initialize()
{
   if( isInitializated() ) return;
   
   /* Check consistency of parameters */
   if(getSizeY()!=1 ||getSizeZ()!=1)
   {
     TPZString err;
     err.sprintf( ERR_TPZTONET_002, (char*)getRouterId() );
     err.sprintf("\nSquare Midimew Network Ysize and Zsize must be 1. Al nodes in Xsize!");
     EXIT_PROGRAM(err); 
   }

   if((int)ceil(sqrt((float)getSizeX()))%2 || getSizeX() < 4 )
   {
     TPZString err;
     err.sprintf( ERR_TPZTONET_002, (char*)getRouterId() );
     err.sprintf("\n Square Midimew Network Xsize must be an even 2's power(4,16,64,256,1024,4096...)");
     EXIT_PROGRAM(err); 
   }

   if( !getSizeX() || !getSizeY() || !getSizeZ() )
   {
      TPZString err;
      err.sprintf(ERR_TPZTONET_001, getSizeX(), getSizeY(), getSizeZ() );
      EXIT_PROGRAM(err);
   }

   /* Create the routers for each node */
   int i;     
   for( i=0; i<getSizeX(); i++ )
   {
      TPZPosition pos(i,0,0);
      TPZRouter* newRouter = (TPZRouter*)
                             (TPZRouter::routerBuilder->createComponentWithId(getRouterId(),this));
      if( ! newRouter )
      {
          TPZString err;
          err.sprintf( ERR_TPZTONET_002, (char*)getRouterId() );
          EXIT_PROGRAM(err);
      }
      newRouter->setPosition(pos);                       
      addRouter(newRouter);
   }

   /* Connect the routers together */
   for( i=0; i<getSizeX(); i++ )
   {
      initializeConnectionsFor(TPZPosition(i,0,0));
   }
  
   /* Other initialization tasks */
   generateRoutingTable();

   setInitializated(true);
   setSimulation(getSimulation());
}
//------------------------------------------------------------------------------
// updateData() -- update non-time critical stuff here
//------------------------------------------------------------------------------
void SimStation::updateData(const LCreal dt)
{
    // ### Don't call updateData for our 'mainDisplay', which is derived from
    // BasicGL::GlutDisplay, because BasicGL::GlutDisplay handles calling updateData() for it's
    // own displays.

    // ---
    // Auto RESET/FREEZE timer --
    // ---
    if ( autoResetTimer > 0 && getSimulation()->isNotFrozen() ) {
       autoResetTimer -= dt;
       if (autoResetTimer <= 0) {
         Basic::Boolean newFrz(true);
         getSimulation()->event(FREEZE_EVENT, &newFrz);
         this->event(RESET_EVENT);
       }
    }

    BaseClass::updateData(dt);
}
TPZString TPZNetworkSquareMidimew :: asString() const
{
   TPZGlobalData& data = ((TPZSimulation*)getSimulation())->globalData((TPZNetwork*)this);
   TPZString rs= "SquareMidimew(";
   rs +=  TPZString(getSizeX()) + "," +
          TPZString(getSizeY()) + "," +
          TPZString(getSizeZ()) + ")" +
          "\n Buffer control : " + data.routerBufferControl() +
          "\n Routing control: " + data.routerRoutingControl();
   return rs;
}
Esempio n. 12
0
dafif::NavaidLoader* NavRadio::getNavaidLoader()
{
   // If we don't have a NAVAID loader, try to get one from our simulation
   if (nvdb == nullptr) {
      Simulation* sim = getSimulation();
      if (sim != nullptr) {
         dafif::NavaidLoader* p = sim->getNavaids();
         if (p != nullptr && p->isDbLoader()) {
            nvdb = p;
         }
      }
   }
   return nvdb;
}
Esempio n. 13
0
dafif::AirportLoader* NavRadio::getAirportLoader()
{
   // If we don't have an airport loader, try to get one from our simulation
   if (apdb == nullptr) {
      Simulation* sim = getSimulation();
      if (sim != nullptr) {
         dafif::AirportLoader* p = sim->getAirports();
         if (p != nullptr && p->isDbLoader()) {
            apdb = p;
         }
      }
   }
   return apdb;
}
Esempio n. 14
0
 /// @param x screen x-coordinate for active camera
 /// @param y screen y-coordinate for active camera
 /// @return the SimEntity intersected first by the ray from the camera origin through the view plane
 SimEntityPtr SimContext::GetClickedEntity(const int32_t& x, const int32_t& y)
 {
     Pos2i pos(x,y);
     // get scene node
     ISceneNode* node = mIrr.getSceneManager()->getSceneCollisionManager()->getSceneNodeFromScreenCoordinatesBB(pos);
     SimEntityPtr result;
     if (node != NULL)
     {
         result = getSimulation()->FindBySceneObjectId(node->getID());
     }
     else
     {
         LOG_F_WARNING("core", "unable to find clicked entity at location " << x << ", " << y);
     }
     return result;
 }
Esempio n. 15
0
void VoxelShapeManager::stepForward(float deltaTime) {
    PhysicsSimulation* simulation = getSimulation();
    if (simulation) {
        glm::vec3 simulationOrigin = simulation->getTranslation();
        if (glm::distance2(_lastSimulationTranslation, simulationOrigin) > EPSILON) {
            VoxelPool::const_iterator voxelItr = _voxels.constBegin();
            while (voxelItr != _voxels.constEnd()) {
                // the shape's position is stored in the simulation-frame
                const VoxelInfo& voxel = voxelItr.value();
                voxel._shape->setTranslation(voxel._cube.calcCenter() - simulationOrigin);
                ++voxelItr;
            }
            _lastSimulationTranslation = simulationOrigin;
        }
    }
}
Esempio n. 16
0
//------------------------------------------------------------------------------
// Process players of interest -- This will work with the function in Gimbal to create
// a filtered list of players that we plan to send emission packets to.
//------------------------------------------------------------------------------
void RfSystem::processPlayersOfInterest()
{
   // ---
   // Do we have an antenna?
   // ---
   if (getAntenna() != 0) {

      // Pass our players of interest to the antenna for processing
      Basic::PairStream* poi = 0;
      Simulation* sim = getSimulation();
      if ( sim != 0 && !areEmissionsDisabled() ) {
         poi = sim->getPlayers();
      }

      getAntenna()->processPlayersOfInterest(poi);

      if (poi != 0) { poi->unref(); poi = 0; }
   }
}
Esempio n. 17
0
void VoxelShapeManager::updateVoxels(const quint64& now, CubeList& cubes) {
    const quint64 VOXEL_UPDATE_PERIOD = 100000; // usec
    _updateExpiry = now + VOXEL_UPDATE_PERIOD;
    PhysicsSimulation* simulation = getSimulation();
    if (!simulation) {
        return;
    }

    int numChanges = 0;
    VoxelPool::iterator voxelItr = _voxels.begin();
    while (voxelItr != _voxels.end()) {
        // look for this voxel in cubes
        CubeList::iterator cubeItr = cubes.find(voxelItr.key());
        if (cubeItr == cubes.end()) {
            // did not find it --> remove the voxel
            simulation->removeShape(voxelItr.value()._shape);
            voxelItr = _voxels.erase(voxelItr);
            ++numChanges;
        } else {
            // found it --> remove the cube
            cubes.erase(cubeItr);
            voxelItr++;
        }
    }

    // add remaining cubes to _voxels
    glm::vec3 simulationOrigin = simulation->getTranslation();
    CubeList::const_iterator cubeItr = cubes.constBegin();
    while (cubeItr != cubes.constEnd()) {
        AACube cube = cubeItr.value();
        AACubeShape* shape = new AACubeShape(cube.getScale(), cube.calcCenter() - simulationOrigin);
        shape->setEntity(this);
        VoxelInfo voxel = {cube, shape };
        _voxels.insert(cubeItr.key(), voxel);
        ++numChanges;
        ++cubeItr;
    }

    if (numChanges > 0) {
        buildShapes();
    }
}
Esempio n. 18
0
    /// @param hitEntity the entity intersected by the ray
    /// @param hitPos the position of the intersection
    /// @param origin origin of the ray to cast
    /// @param target target of the ray to cast
    /// @param type bitmask of the objects to care about or 0 for 'check all'
    /// @param vis show rays?
    /// @param foundColor the color to use if vis is true and an intersection is found
    /// @param noneColor the color to use if vis is true 
    /// @return first intersection info tuple(sim, hit) with SimEntityData sim and Vector3f hit (hit location) or ()
    /// Find the first object that intersects the specified ray
    bool SimContext::FindInRay( SimEntityData& hitEntity,
                                Vector3f& hitPos,
                                const Vector3f& origin, 
                                const Vector3f& target, 
                                const uint32_t& type, 
                                const bool vis, 
                                const SColor& foundColor,
                                const SColor& noneColor
                              )
	{
        ISceneCollisionManager* collider = mIrr.getSceneManager()->getSceneCollisionManager();
        Assert(collider);
        Line3f ray(ConvertNeroToIrrlichtPosition(origin), ConvertNeroToIrrlichtPosition(target));
        Triangle3f outTriangle;
        ISceneNode* node = collider->getSceneNodeAndCollisionPointFromRay
            (ray, hitPos, outTriangle, type);
        // convert back into our coord system
        hitPos = ConvertIrrlichtToNeroPosition(hitPos);
        if (node && node->getID() >= kFirstSimId)
        {
            // we found a sim node, so return its data
            SimEntityPtr ent = getSimulation()->FindBySceneObjectId(node->getID());
            if (ent)
            {
                // return the result: (sim, hit)
                hitEntity = ent->GetState();
                // draw a ray if requested
                if (vis)
                {
                    LineSet::instance().AddSegment(origin, hitPos, foundColor);
                }
                return true;
            }
        }
        if (vis)
        {
            LineSet::instance().AddSegment(origin, target, noneColor);
        }
        return false;
	}
Esempio n. 19
0
//------------------------------------------------------------------------------
// reset() -- Reset parameters
//------------------------------------------------------------------------------
void Navigation::reset()
{
   BaseClass::reset();

   // And not nothin' valid
   posValid = false;
   attValid = false;
   velValid = false;
   magVarValid = false;
   navStrValid = false;

   // Except UTC
   utc = initUTC;
   utcValid = true;

   // Reset the route to the initial route and reset
   if (priRoute != 0) {
      priRoute->container(0);
      priRoute = 0;
   }
   if (initRoute != 0) {
      priRoute = initRoute->clone();
      priRoute->unref();  // SPtr<> has it
   }
   if (priRoute != 0) {
      priRoute->container(this);
      priRoute->event(RESET_EVENT);
   }

   // Reset our bullseye
   if (bull != 0) bull->event(RESET_EVENT);

   // Set the reference center of our gaming area
   const Simulation* sim = getSimulation();
   if (sim != 0) {
      refLat = sim->getRefLatitude();
      refLon = sim->getRefLongitude();     
   }
}
void LifeForm::fire()
{
    Basic::Number* hdgObj = new Basic::Number(getHeadingR());
    Basic::Number* pitchObj = new Basic::Number(lookAngle * Basic::Angle::D2RCC);
    StoresMgr* mgr = getStoresManagement();
    if (mgr != nullptr) {
        if (getSimulation() != nullptr) {
            if (weaponSel == LF_MISSILE) {
                mgr->setGunSelected(false);
                Missile* missile = mgr->getNextMissile();
                if (missile != nullptr) {
                    missile->setSlotInitPitch(pitchObj);
                    missile->setSlotInitHeading(hdgObj);
                    missile->reset();
                    Missile* msl = mgr->releaseOneMissile();
                    if (msl != nullptr) {
                        if (tgtAquired && tgtPlayer != nullptr) msl->setTargetPlayer(tgtPlayer, true);
                    }
                }
            }
            else if (weaponSel == LF_GUN) {
                mgr->setGunSelected(true);
                Gun* myGun = mgr->getGun();
                if (myGun != nullptr) {
                    myGun->setGunArmed(true);
                    Basic::Number* num = new Basic::Number(lookAngle * Basic::Angle::D2RCC);
                    myGun->setSlotPitch(num);
                    num->unref();
                    myGun->fireControl(true);
                }
           }
        }
    }
    hdgObj->unref();
    pitchObj->unref();
}
Esempio n. 21
0
//------------------------------------------------------------------------------
// process() -- 
//------------------------------------------------------------------------------
void Sar::process(const LCreal dt)
{
    BaseClass::process(dt);

    // Imaging in porgress?
   if (timer > 0) {

      // ---
      // Point the beam
      // ---
      Antenna* ant = getAntenna();
      if (ant != 0) {
         
         Simulation* s = getSimulation();
         double refLat = s->getRefLatitude();
         double refLon = s->getRefLongitude();

         osg::Vec3 pos;
         Basic::Nav::convertLL2PosVec(
            refLat, refLon,                           // Ref point (at sea level)
            getStarePointLatitude(), getStarePointLongitude(), getStarePointElevation(), 
            &pos); // x,y,z  NED

         // Platform (ownship) coord and then body
         osg::Vec3 posP = pos - getOwnship()->getPosition();
         osg::Vec3 posB = getOwnship()->getRotMat() * posP;

         // Convert to az/el
         LCreal tgt_az = 0.0;   // Angle (degs)
         LCreal tgt_el = 0.0;   // Angle (degs)
         xyz2AzEl(posB, &tgt_az, &tgt_el);

         // Command to that position
         LCreal az = tgt_az * (LCreal)Basic::Angle::D2RCC;
         LCreal el = tgt_el * (LCreal)Basic::Angle::D2RCC;

         ant->setRefAzimuth(az);
         ant->setRefElevation(el);
         ant->setScanMode(Antenna::CONICAL_SCAN);
      }

      // ---
      // Process timer
      // ---
      LCreal ttimer = timer - dt;
      if (ttimer <= 0) {

         // ### test -- Generate a test image ###
         Image* p = new Image();
         p->testImage(width,height);
         p->setImageId(getNextId());
         p->setLatitude(getStarePointLatitude());
         p->setLongitude(getStarePointLongitude());
         p->setElevation(getStarePointElevation());
         p->setOrientation(0);
         if (isMessageEnabled(MSG_INFO)) {
            std::cout << "Sar:: Generating test image: resolution: " << getResolution() << std::endl;
         }
         if (getResolution() > 0) p->setResolution( getResolution() );
         else p->setResolution( 3.0f * Basic::Distance::FT2M );
         Basic::Pair* pp = new Basic::Pair("image", p);
         addImage(pp);
         // ### TEST TEST 

         // Just finished!
         ttimer = 0;
         setTransmitterEnableFlag(false);
      }
      timer = ttimer;
   }

   BaseClass::updateData(dt);
}
Esempio n. 22
0
//------------------------------------------------------------------------------
// sendMessage() -- send the datalink message out to the world.
//------------------------------------------------------------------------------
bool Datalink::sendMessage(Basic::Object* const msg)
{
   bool sent = false;

   // If we can send to our local players directly (or via radio)
   if (sendLocal) {
      // ---
      // Have a comm radio -- then we'll just let our companion radio system handle this
      // ---
      if (radio != 0) {
         sent = radio->transmitDataMessage(msg);
      }

      // ---
      // No comm radio -- then we'll send this out to the other players ourself.
      // ---
      else if (getOwnship() != 0) {
         Simulation* sim = getSimulation();
         if (sim != 0) {

            Basic::PairStream* players = sim->getPlayers();
            if (players != 0) {

            Basic::List::Item* playerItem = players->getFirstItem();
            while (playerItem != 0) {

               Basic::Pair* playerPair = static_cast<Basic::Pair*>(playerItem->getValue());
               Player* player = static_cast<Player*>(playerPair->object());

               if (player->isLocalPlayer()) {
                  // Send to active, local players only (and not to ourself)
                     if ((player->isActive() || player->isMode(Player::PRE_RELEASE)) && player != getOwnship() ) {
                     player->event(DATALINK_MESSAGE, msg);
                  }
                  playerItem = playerItem->getNext();
               }
               else {
                  // Networked players are at the end of the list,
                  // so we can stop now.
                  playerItem = 0;
               }

            }

               players->unref();
               players = 0;
            }
         }
         sent = true;
      }
   }

   // ---
   // and let any (optional) outgoing queue know about this.
   // ---
   if (queueForNetwork) {
      Player* ownship = getOwnship();
      if (ownship != 0) {
         if (ownship->isLocalPlayer()) {
            queueOutgoingMessage(msg);
         }
      }
   }

   return sent;
}
Esempio n. 23
0
/**-------------------------------------------------------------------------------
	~SensorDecoratorVector
	
	@brief
	@return 
---------------------------------------------------------------------------------*/
SensorDecoratorVector::~SensorDecoratorVector()
{
	Ogre::MaterialManager::getSingleton().remove(mName + "Material");
	getSimulation()->getScene()->getSceneManager().getRootSceneNode()->removeAndDestroyChild(mName + "_node");
}
Esempio n. 24
0
//------------------------------------------------------------------------------
// weaponGuidance() -- default guidance; using Robot Aircraft (RAC) guidance
//------------------------------------------------------------------------------
void Missile::weaponGuidance(const LCreal dt)
{
   // ---
   // Control velocity:  During burn time, accel to max velocity,
   //  after burn time, deaccelerate to min velocity.
   // ---
   if (isEngineBurnEnabled()) cmdVelocity = vpMax;
   else cmdVelocity = vpMin;

   // ---
   // If the target's already dead,
   //    then don't go away mad, just go away.
   // ---
   const Player* tgt = getTargetPlayer();
   const Track* trk = getTargetTrack();
   if (trk != 0) tgt = trk->getTarget();

   if (tgt != 0 && !tgt->isActive()) return;

   osg::Vec3 los; // Target Line of Sight
   osg::Vec3 vel; // Target velocity

   // ---
   // Basic guidance
   // ---
   {
      // ---
      // Get position and velocity vectors from the target/track
      // ---
      osg::Vec3 posx;
      calculateVectors(tgt, trk, &los, &vel, &posx);

      // compute range to target
      LCreal trng0 = trng;
      trng = los.length();

      // compute range rate,
      //LCreal trdot0 = trdot;
      if (dt > 0)
         trdot = (trng - trng0)/dt;
      else
         trdot = 0;

      // Target total velocity
      LCreal totalVel = vel.length();

      // compute target velocity parallel to LOS,
      LCreal vtplos = (los * vel/trng);

      // ---
      // guidance - fly to intercept point
      // ---

      // if we have guidance ...
      if ( isGuidanceEnabled() && trng > 0) {

         // get missile velocity (must be faster than target),
         LCreal v = vpMax;
         if (v < totalVel) v = totalVel + 1;

         // compute target velocity normal to LOS squared,
         LCreal tgtVp = totalVel;
         LCreal vtnlos2 = tgtVp*tgtVp - vtplos*vtplos;

         // and compute missile velocity parallex to LOS.
         LCreal vmplos = lcSqrt( v*v - vtnlos2 );

         // Now, use both velocities parallel to LOS to compute
         //  closure rate.
         LCreal vclos = vmplos - vtplos;

         // Use closure rate and range to compute time to intercept.
         LCreal dt1 = 0;
         if (vclos > 0) dt1 = trng/vclos;

         // Use time to intercept to extrapolate target position.
         osg::Vec3 p1 = (los + (vel * dt1));

         // Compute missile commanded heading and
         cmdHeading = lcAtan2(p1.y(),p1.x());

         // commanded pitch.
         LCreal grng = lcSqrt(p1.x()*p1.x() + p1.y()*p1.y());
         cmdPitch = -lcAtan2(p1.z(),grng);

      }
   }

   // ---
   // fuzing logic  (let's see if we've scored a hit)
   //  (compute range at closest point and compare to max burst radius)
   //  (use target truth data)
   // ---
   {
      // ---
      // Get position and velocity vectors from the target (truth)
      // (or default to the values from above)
      // ---
      if (tgt != 0) {
         calculateVectors(tgt, 0, &los, &vel, 0);
      }

      // compute range to target
      LCreal trng0 = trngT;
      trngT = los.length();

      // compute range rate,
      LCreal trdot0 = trdotT;
      if (dt > 0)
         trdotT = (trngT - trng0)/dt;
      else
         trdotT = 0;

      // when we've just passed the target ...
      if (trdotT > 0 && trdot0 < 0 && !isDummy() && getTOF() > 2.0f) {
         bool missed = true;   // assume the worst

         // compute relative velocity vector.
         osg::Vec3 velRel = (vel - getVelocity());

         // compute missile velocity squared,
         LCreal vm2 = velRel.length2();
         if (vm2 > 0) {

            // relative range (dot) relative velocity
            LCreal rdv = los * velRel;

            // interpolate back to closest point
            LCreal ndt = -rdv/vm2;
            osg::Vec3 p0 = los + (velRel*ndt);

            // range squared at closest point
            LCreal r2 = p0.length2();

            // compare to burst radius squared
            if (r2 <= (getMaxBurstRng()*getMaxBurstRng()) ) {

               // We've detonated
               missed = false;
               setMode(DETONATED);
               setDetonationResults( DETONATE_ENTITY_IMPACT );

               // compute location of the detonation relative to the target
               osg::Vec3 p0n = -p0;
               if (tgt != 0) p0n = tgt->getRotMat() * p0n;
               setDetonationLocation(p0n);

               // Did we hit anyone?
               checkDetonationEffect();

               // Log the event
               LCreal detRange = getDetonationRange();
               if (isMessageEnabled(MSG_INFO)) {
                  std::cout << "DETONATE_ENTITY_IMPACT rng = " << detRange << std::endl;
               }

               BEGIN_RECORD_DATA_SAMPLE( getSimulation()->getDataRecorder(), REID_WEAPON_DETONATION )
                  SAMPLE_3_OBJECTS( getLaunchVehicle(), this, getTargetPlayer() )
                  SAMPLE_2_VALUES( DETONATE_ENTITY_IMPACT, detRange )
               END_RECORD_DATA_SAMPLE()

               // TabLogger is deprecated
               if (getAnyEventLogger() != 0) {
                  TabLogger::TabLogEvent* evt = new TabLogger::LogWeaponActivity(2, getLaunchVehicle(), this, getTargetPlayer(), DETONATE_ENTITY_IMPACT, detRange); // type 2 for "detonate"
                  getAnyEventLogger()->log(evt);
                  evt->unref();
               }
            }
         }
Esempio n. 25
0
Node* DAGNode::findCommonParent( simulation::Node* node2 )
{
    return static_cast<DAGNode*>(getSimulation()->GetRoot().get())->findCommonParent( this, static_cast<DAGNode*>(node2) );
}
void LifeForm::look(const LCreal up, const LCreal sdws)
{
    if (getDamage() < 1) {
        if (lockMode != LOCKED) {
            lockMode = SEARCHING;
            // our up and sideways come in as -5 to 5, which is a rate to adjust heading
            const osg::Vec3 old = getEulerAngles();
            LCreal hdg = old.z();
            LCreal ptc = lookAngle;
            LCreal tempSdws = sdws;
            LCreal tempUp = up;
            if (lcAbs(tempSdws) < 0.00005) tempSdws = 0;
            if (lcAbs(tempUp) < 0.05) tempUp = 0;
            hdg += tempSdws;
            hdg = lcAepcRad(hdg);
            // we don't change our pitch when we look up and down, we only change our look angle, so we have to keep
            // that separate.  WE do, however, change our heading based on where we are looking, so that is correct
            ptc += tempUp;
            if (ptc > 90) ptc = 90;
            else if (ptc < -90) ptc = -90;
            //std::cout << "HEADING = " << hdg << std::endl;
            setLookAngle(ptc);
            osg::Vec3 eul(0, 0, hdg);
            setEulerAngles(eul);
            // now based on this we need to know if we have a target in our crosshairs...
            tgtAquired = false;
            if (tgtPlayer != nullptr) tgtPlayer->unref();
            tgtPlayer = nullptr;
            const osg::Vec3 myPos = getPosition();
            osg::Vec3 tgtPos;
            osg::Vec3 vecPos;
            LCreal az = 0.0, el = 0.0, range = 0.0, diffAz = 0.0, diffEl = 0.0;
            const LCreal maxAz = (0.7f * static_cast<LCreal>(Basic::Angle::D2RCC));
            const LCreal maxEl = (0.7f * static_cast<LCreal>(Basic::Angle::D2RCC));
            //LCreal maxRange = 1500.0f; // long range right now
            const LCreal la = lookAngle * static_cast<LCreal>(Basic::Angle::D2RCC);
            Simulation* sim = getSimulation();
            if (sim != nullptr) {
                Basic::PairStream* players = sim->getPlayers();
                if (players != nullptr) {
                    Basic::List::Item* item = players->getFirstItem();
                    while (item != nullptr && !tgtAquired) {
                        Basic::Pair* pair = static_cast<Basic::Pair*>(item->getValue());
                        if (pair != nullptr) {
                            Player* player = dynamic_cast<Player*>(pair->object());
                            if (player != nullptr && player != this && !player->isMajorType(WEAPON) && !player->isDestroyed()) {
                                // ok, calculate our position from this guy
                                tgtPos = player->getPosition();
                                vecPos = tgtPos - myPos;
                                az = lcAtan2(vecPos.y(), vecPos.x());
                                range = (vecPos.x() * vecPos.x() + vecPos.y() * vecPos.y());
                                range = std::sqrt(range);
                                // now get our elevation
                                el = lcAtan2(-vecPos.z(), range);
                                diffAz = lcAbs(lcAepcRad(az - static_cast<LCreal>(getHeadingR())));
                                diffEl = lcAbs(lcAepcRad(la - el));
                                if ((diffAz <= maxAz) && (diffEl <= maxEl)) {
                                    lockMode = TGT_IN_SIGHT;
                                    tgtAquired = true;
                                    if (tgtPlayer != player) {
                                        if (tgtPlayer != nullptr) tgtPlayer->unref();
                                        tgtPlayer = player;
                                        tgtPlayer->ref();
                                    }
                                }
                            }
                        }
                        item = item->getNext();
                    }
                    players->unref();
                    players = nullptr;
                }
            }
        }
        // else we are locking on target, and need to follow our target player
        else {
            if (tgtPlayer == nullptr) lockMode = SEARCHING;
            else {
                const osg::Vec3 vecPos = tgtPlayer->getPosition() - getPosition();
                const LCreal az = lcAtan2(vecPos.y(), vecPos.x());
                LCreal range = (vecPos.x() * vecPos.x() + vecPos.y() * vecPos.y());
                range = std::sqrt(range);
                // now get our elevation
                const LCreal el = lcAtan2(-vecPos.z(), range);
                // now force that on us
                setLookAngle(el * static_cast<LCreal>(Basic::Angle::R2DCC));
                setEulerAngles(0, 0, az);
            }
        }
    }
}
Esempio n. 27
0
//------------------------------------------------------------------------------
// checkForTargetHit() -- check to see if we hit anything
//------------------------------------------------------------------------------
bool Bullet::checkForTargetHit()
{
   Player* ownship = getLaunchVehicle();
   Player* tgt = getTargetPlayer();
   if (ownship != nullptr && tgt != nullptr) {
      osg::Vec3 osPos = tgt->getPosition();

      // For all active bursts ...
      for (int i = 0; i < nbt; i++) {
         if (bursts[i].bStatus == Burst::ACTIVE) {

            // Check if we're within range of the target
            osg::Vec3 rPos = bursts[i].bPos - osPos;
            LCreal rng = rPos.length();
            if (rng < 10.0) {
               // Yes -- it's a hit!
               bursts[i].bStatus = Burst::HIT;
               setHitPlayer(tgt);
               setLocationOfDetonation();
               tgt->processDetonation(rng,this);
            }

         }
      }
   }
   // if we are just flying along, check our range to the nearest player and tell him we killed it
   else {
        //osg::Vec3 old = getEulerAngles();
        osg::Vec3 myPos = getPosition();
        osg::Vec3 tgtPos;
        osg::Vec3 vecPos;
        //LCreal az = 0;
        //LCreal el = 0;
        LCreal range = 0;
        //LCreal diffAz = 0;
        //LCreal diffEl = 0;
        LCreal maxRange = 1; // close range of detonation
        Simulation* sim = getSimulation();
        if (sim != nullptr) {
            Basic::PairStream* players = sim->getPlayers();
            if (players != nullptr) {
                Basic::List::Item* item = players->getFirstItem();
                while (item != nullptr) {
                    Basic::Pair* pair = static_cast<Basic::Pair*>(item->getValue());
                    if (pair != nullptr) {
                        Player* player = dynamic_cast<Player*>(pair->object());
                        if (player != nullptr && player != ownship && player->isMajorType(LIFE_FORM) && !player->isDestroyed()) {
                            // ok, calculate our position from this guy
                            tgtPos = player->getPosition();
                            vecPos = tgtPos - myPos;
                            //az = lcAtan2(vecPos.y(), vecPos.x());
                            range = (vecPos.x() * vecPos.x() + vecPos.y() * vecPos.y());
                            range = std::sqrt(range);
                            if (range < maxRange) {
                                // tell this target we hit it
                                player->processDetonation(range, this);
                            }
                        }
                    }
                    item = item->getNext();
                }
                players->unref();
                players = nullptr;
            }
        }

   }
   return false;
}
Esempio n. 28
0
void Component::killEntity(EntityID entity)
{
	getSimulation()->killEntity(entity);
}
//------------------------------------------------------------------------------
// processDetonationPDU() callback --
//------------------------------------------------------------------------------
void NetIO::processDetonationPDU(const DetonationPDU* const pdu)
{
   // Get the Firing Player's ID
   unsigned short fPlayerId = pdu->firingEntityID.ID;
   unsigned short fSiteId = pdu->firingEntityID.simulationID.siteIdentification;
   unsigned short fApplicationId = pdu->firingEntityID.simulationID.applicationIdentification;

   // Ignore our own PDUs
   if (fSiteId == getSiteID() && fApplicationId == getApplicationID()) return;

   // Get the Munition Player's ID
   unsigned short mPlayerId = pdu->munitionID.ID;
   unsigned short mSiteId = pdu->munitionID.simulationID.siteIdentification;
   unsigned short mApplicationId = pdu->munitionID.simulationID.applicationIdentification;

   // Get the Target Player's ID
   unsigned short tPlayerId = pdu->targetEntityID.ID;
   unsigned short tSiteId = pdu->targetEntityID.simulationID.siteIdentification;
   unsigned short tApplicationId = pdu->targetEntityID.simulationID.applicationIdentification;

   // ---
   // 1) Find the target player
   // ---
   simulation::Player* tPlayer = nullptr;
   if (tPlayerId != 0 && tSiteId != 0 && tApplicationId != 0) {
      simulation::Nib* tNib = findDisNib(tPlayerId, tSiteId, tApplicationId, OUTPUT_NIB);
      if (tNib != nullptr) {
         tPlayer = tNib->getPlayer();
      }
   }
   //std::cout << "Net kill(2) tPlayer = " << tPlayer << std::endl;

   // ---
   // 2) Find the firing player and munitions (networked) IPlayers
   // ---
   simulation::Player* fPlayer = nullptr;
   if (fPlayerId != 0 && fSiteId != 0 && fApplicationId != 0) {
      simulation::Nib* fNib = findDisNib(fPlayerId, fSiteId, fApplicationId, INPUT_NIB);
      if (fNib != nullptr) {
         fPlayer = fNib->getPlayer();
      }
      else {
         base::safe_ptr<base::PairStream> players( getSimulation()->getPlayers() );
         fPlayer = getSimulation()->findPlayer(fPlayerId);
      }
   }

   simulation::Nib* mNib = nullptr;
   if (mPlayerId != 0 && mSiteId != 0 && mApplicationId != 0) {
      mNib = findDisNib(mPlayerId, mSiteId, mApplicationId, INPUT_NIB);
   }

    //std::cout << "Net kill(3) fNib = " << fNib << ", mNib = " << mNib << std::endl;

   // ---
   // 3) Update the data of the munition's NIB and player
   // ---
   simulation::Weapon* mPlayer = nullptr;
   if (mNib != nullptr) {

      // ---
      // a) Set the munition's NIB to the location of the detonation
      // ---

      // Get the geocentric position, velocity and acceleration from the PDU
      osg::Vec3d geocPos;
      geocPos[base::Nav::IX] = pdu->location.X_coord;
      geocPos[base::Nav::IY] = pdu->location.Y_coord;
      geocPos[base::Nav::IZ] = pdu->location.Z_coord;

      osg::Vec3d geocVel;
      geocVel[base::Nav::IX] = pdu->velocity.component[0];
      geocVel[base::Nav::IY] = pdu->velocity.component[1];
      geocVel[base::Nav::IZ] = pdu->velocity.component[2];

      osg::Vec3d geocAcc(0,0,0);
      osg::Vec3d geocAngles(0,0,0);
      osg::Vec3d arates(0,0,0);

      // (re)initialize the dead reckoning function
      mNib->resetDeadReckoning(
         simulation::Nib::STATIC_DRM,
         geocPos,
         geocVel,
         geocAcc,
         geocAngles,
         arates);

      // Set the NIB's mode to DETONATED
      mNib->setMode(simulation::Player::DETONATED);

      // Find the munition player and set its mode, location and target position
      mPlayer = dynamic_cast<simulation::Weapon*>(mNib->getPlayer());
      if (mPlayer != nullptr) {

         // Munition's mode
         mPlayer->setMode(simulation::Player::DETONATED);

         // munition's position, velocity and acceleration at the time of the detonation
         mPlayer->setGeocPosition(geocPos);
         mPlayer->setGeocVelocity(geocVel);
         mPlayer->setGeocAcceleration(geocAcc);

         // detonation results
         mPlayer->setDetonationResults(simulation::Weapon::Detonation(pdu->detonationResult));

         // Munition's target player and the location of detonation relative to target
         mPlayer->setTargetPlayer(tPlayer,false);
         double x = pdu->locationInEntityCoordinates.component[0];
         double y = pdu->locationInEntityCoordinates.component[1];
         double z = pdu->locationInEntityCoordinates.component[2];
         osg::Vec3 loc(x,y,z);
         mPlayer->setDetonationLocation(loc);

         // Munition's launcher
         if (mPlayer->getLaunchVehicle() == nullptr && fPlayer != nullptr) {
            mPlayer->setLaunchVehicle(fPlayer);
         }
      }
   }

   // ---
   // 4) Check all local players for the effects of the detonation
   // ---
   if (mPlayer != nullptr) {
      mPlayer->checkDetonationEffect();
   }
}
Esempio n. 30
0
//------------------------------------------------------------------------------
// burstFrame() -- generate a small burst of bullets (usually every 1/10 seconds)
//------------------------------------------------------------------------------
void Gun::burstFrame()
{
   // Compute the number of rounds this burst
   int ibullets = static_cast<int>(rcount + 0.5f);

   // Do we have any bullets to fire ...
   if (ibullets > 0){

      // Decrease the number of rounds remaining
      if ( !isUnlimited() ) {
         if (ibullets > rounds) {
            ibullets = rounds;
            rcount = LCreal(ibullets);
         }
         rounds -= ibullets;
      }


      // Update the rounds fired count
      rcount -= ibullets;

      // Log this event
      Player* ownship = static_cast<Player*>( findContainerByType(typeid(Player)) );

      if (ownship != 0) {
         BEGIN_RECORD_DATA_SAMPLE( getSimulation()->getDataRecorder(), REID_GUN_FIRED )
            SAMPLE_1_OBJECT( ownship )
            SAMPLE_1_VALUE( rcount )
         END_RECORD_DATA_SAMPLE()
      }

      // TabLogger is deprecated
      if (ownship != nullptr && getAnyEventLogger() != nullptr) {
         TabLogger::TabLogEvent* evt = new TabLogger::LogGunActivity(1, ownship, ibullets); // type 1 == gun fired
         getAnyEventLogger()->log(evt);
         evt->unref();
      }

      // When we have a bullet model ... we're going to create a bullet (weapon)
      // player to flyout the rounds.
      Bullet* wpn = getBulletType();
      Simulation* sim = static_cast<Simulation*>( findContainerByType(typeid(Simulation)) );
      if (wpn != nullptr && ownship != nullptr && sim != nullptr) {

         // Compute the bullet burst's initial position and velocity
         osg::Vec3 ipos = computeInitBulletPosition();
         osg::Vec3 ivel = computeInitBulletVelocity();

         // Get the bullet player being used to fly-out the bullets
         Bullet* flyout = static_cast<Bullet*>( wpn->getFlyoutWeapon() );
         if (flyout == nullptr) {
            // If we don't have the flyout bullet (i.e., weapon and player) ... create it
            wpn->setLaunchVehicle(ownship);
            flyout = static_cast<Bullet*>( wpn->release() );
         }

            // The flyout bullet (player) will handle this burst of bullets.
         if (flyout != nullptr) {
            flyout->burstOfBullets(&ipos, &ivel, ibullets, getRoundsPerMinute(), sim->getNewWeaponEventID() );
         }

         // Cleanup
         if (flyout != nullptr) { flyout->unref(); flyout = nullptr; }

      }
   }
   else rcount = 0;