void
DistributedDVFSManager::receiveKernelMessage(KernelMessage* kMsg) {
  UsefulWorkMessage* msg = dynamic_cast<UsefulWorkMessage*>(kMsg);
  ASSERT(msg);

  std::vector<double> dat;
  UsefulWorkMessage::MessageRound round = msg->getRound();
  bool idxsChanged = false;
  msg->getData(dat);
  if(round == UsefulWorkMessage::COLLECT) {
    fillUsefulWork(dat);
    if(isMaster()) {
      for(int i = 0; i < dat.size(); i++)
        myUtilFilters[i].update(dat[i]);

      if(!isDummy())
        idxsChanged = updateFrequencyIdxs();

      if(debugPrint())
        for(int i = 0; i < dat.size(); i++)
          writeCSVRow(i, 
                      myUtilFilters[i].getData(), 
                      myAvailableFreqs[myFrequencyIdxs[i]]);
    }
  }
  else if(round == UsefulWorkMessage::SETFREQ && !isDummy())
    setFrequencies(static_cast<int>(dat[mySimulationManagerID]));

  // forward message to next node unless we're the master and either
  // we just received a set frequency message or the frequencies haven't changed
  if(!(isMaster() && (round == UsefulWorkMessage::SETFREQ || !idxsChanged))) {
    int dest = (mySimulationManagerID + 1) % myNumSimulationManagers;
    UsefulWorkMessage::MessageRound newRound =
        isMaster() ? UsefulWorkMessage::SETFREQ : round;

    UsefulWorkMessage* newMsg = new UsefulWorkMessage(mySimulationManagerID,
                                                        dest,
                                                        myNumSimulationManagers,
                                                        newRound);

    if(isMaster())
      for(int i=0; i < myFrequencyIdxs.size(); i++)
        dat[i] = static_cast<double>(myFrequencyIdxs[i]);

    newMsg->setData(dat);
    myCommunicationManager->sendMessage(newMsg, dest);
  }
  else
    myWaitingForMessage = false;

  delete kMsg;
}
Exemple #2
0
s16 MapBlock::getGroundLevel(v2s16 p2d)
{
	if(isDummy())
		return -3;
	try
	{
		s16 y = MAP_BLOCKSIZE-1;
		for(; y>=0; y--)
		{
			MapNode n = getNodeRef(p2d.X, y, p2d.Y);
			if(m_gamedef->ndef()->get(n).walkable)
			{
				if(y == MAP_BLOCKSIZE-1)
					return -2;
				else
					return y;
			}
		}
		return -1;
	}
	catch(InvalidPositionException &e)
	{
		return -3;
	}
}
Exemple #3
0
//*************************************************************
// returns number of dummies
int SimDraw::numberOfDummyNodes() const
{
	int counter = 0;
	for(node v : m_G.nodes)
		if(isDummy(v))
			counter++;
	return counter;

} // end numberOfDummyNodes
QString Project::makeAbsolute( const QString &f )
{
    if ( isDummy() )
	return f;
    QString encodedUrl = QFileInfo( filename ).dirPath( TRUE );
    QUrl::encode( encodedUrl );
    QUrl u( encodedUrl, f );
    return u.path();
}
Exemple #5
0
//*************************************************************
// returns number of dummies
int SimDraw::numberOfDummyNodes() const
{
    int counter = 0;
    node v;
    forall_nodes(v, m_G)
	if(isDummy(v))
	    counter++;
    return counter;

} // end numberOfDummyNodes
Exemple #6
0
bool BCMarker::valid() const {
  if (isDummy()) return true;
  return
    m_sk.valid() &&
    m_sk.offset() >= m_sk.func()->base() &&
    m_sk.offset() < m_sk.func()->past() &&
    (RuntimeOption::EvalHHIREnableGenTimeInlining ||
     m_spOff <= m_sk.func()->numSlotsInFrame() + m_sk.func()->maxStackCells());
  // When inlining is on, we may modify markers to weird values in case reentry
  // happens.
}
 // adds an edge. Invalidates edge iterators for the source node
 EdgeIterator InsertEdge(const NodeIterator from, const NodeIterator to, const EdgeDataT &data)
 {
     Node &node = node_list[from];
     EdgeIterator newFirstEdge = node.edges + node.firstEdge;
     if (newFirstEdge >= edge_list.size() || !isDummy(newFirstEdge))
     {
         if (node.firstEdge != 0 && isDummy(node.firstEdge - 1))
         {
             node.firstEdge--;
             edge_list[node.firstEdge] = edge_list[node.firstEdge + node.edges];
         }
         else
         {
             EdgeIterator newFirstEdge = (EdgeIterator)edge_list.size();
             unsigned newSize = node.edges * 1.1 + 2;
             EdgeIterator requiredCapacity = newSize + edge_list.size();
             EdgeIterator oldCapacity = edge_list.capacity();
             if (requiredCapacity >= oldCapacity)
             {
                 edge_list.reserve(requiredCapacity * 1.1);
             }
             edge_list.resize(edge_list.size() + newSize);
             for (const auto i : osrm::irange(0u, node.edges))
             {
                 edge_list[newFirstEdge + i] = edge_list[node.firstEdge + i];
                 makeDummy(node.firstEdge + i);
             }
             for (const auto i : osrm::irange(node.edges + 1, newSize))
             {
                 makeDummy(newFirstEdge + i);
             }
             node.firstEdge = newFirstEdge;
         }
     }
     Edge &edge = edge_list[node.firstEdge + node.edges];
     edge.target = to;
     edge.data = data;
     ++number_of_edges;
     ++node.edges;
     return EdgeIterator(node.firstEdge + node.edges);
 }
Exemple #8
0
void ScreenModeChecker::enable()
{
	if (isDummy())
		return;

	if (!FullScreenCheckTimer)
		FullScreenCheckTimer = new QTimer(this);

	FullScreenCheckTimer->setInterval(FULLSCREENCHECKTIMER_INTERVAL);
	connect(FullScreenCheckTimer, SIGNAL(timeout()), this, SLOT(checkFullScreen()));
	FullScreenCheckTimer->start();
}
Exemple #9
0
//*************************************************************
// checks whether node is a proper dummy node
// proper dummy means that node is marked as dummy and 
// incident edges have at least one common input graph
bool SimDraw::isProperDummy(node v) const
{
    if(!isDummy(v))
	return false;
    int sgb = m_GA.subGraphBits(v->firstAdj()->theEdge());
    edge e;
    forall_adj_edges(e, v)
	sgb &= m_GA.subGraphBits(e);
    
    return (sgb != 0);

} // end isProperDummy
QString Project::makeRelative( const QString &f )
{
    if ( isDummy() )
	return f;
    QString p = QFileInfo( filename ).dirPath( TRUE );    
    QString f2 = f;
#if defined(Q_WS_WIN32)
    if ( p.endsWith("/") )
        p = p.left( p.length() - 1 );
    if ( f2.left( p.length() ).lower() == p.lower() )
#else
    if ( f2.left( p.length() ) == p )
#endif
	    f2.remove( 0, p.length() + 1 );
    return f2;
}
//----------------------------------------------------------------------------//
void GridLayoutContainer::removeChild_impl(Element* element)
{
    Window* wnd = static_cast<Window*>(element);
    
    if (!isDummy(wnd) && !WindowManager::getSingleton().isLocked())
    {
        // before we remove the child, we must add new dummy and place it
        // instead of the removed child
        Window* dummy = createDummy();
        addChild(dummy);

        const size_t i = getIdxOfChild(wnd);
        std::swap(d_children[i], d_children[d_children.size() - 1]);
    }

    LayoutContainer::removeChild_impl(wnd);
}
Exemple #12
0
bool TempSpriteHandler::load(int16 dataVar, int32 size, int32 offset) {
	if (isDummy(size))
		return true;

	// Sprite available?
	if (!_sprite)
		return false;

	// Sprite requested?
	if (!isSprite(size))
		return false;

	// Index sane?
	int index = getIndex(size);
	if ((index < 0) || (index >= Draw::kSpriteCount))
		return false;

	SurfacePtr sprite = _vm->_draw->_spritesArray[index];

	// Target sprite exists?
	if (!sprite)
		return false;

	// Load the sprite
	if (!_sprite->writeSprite(*sprite))
		return false;

	// Handle palette
	if (usesPalette(size)) {
		if (!_sprite->writePalette((byte *)_vm->_global->_pPaletteDesc->vgaPal))
			return false;

		_vm->_video->setFullPalette(_vm->_global->_pPaletteDesc);
	}

	if (index == 21) {
		// We wrote into the backbuffer, blit
		_vm->_draw->forceBlit();
		_vm->_video->retrace();
	} else if (index == 20)
		// We wrote into the frontbuffer, retrace
		_vm->_video->retrace();

	return true;
}
Exemple #13
0
bool TempSpriteHandler::save(int16 dataVar, int32 size, int32 offset) {
	if (isDummy(size))
		return true;

	SurfacePtr sprite = createSprite(dataVar, size, offset);
	if (!sprite)
		return false;

	// Save the sprite
	if (!_sprite->readSprite(*sprite))
		return false;

	// Handle palette
	if (usesPalette(size))
		if (!_sprite->readPalette((const byte *)_vm->_global->_pPaletteDesc->vgaPal))
			return false;

	return true;
}
Exemple #14
0
//
// Looks for the given weapon  in an indexed slot
//
static weaponslot_t *E_findEntryForWeaponInSlot(const player_t *player, const weaponinfo_t *wp,
                                                const weaponslot_t *slot)
{
   if(slot == nullptr)
      return nullptr;

   auto baseslot = E_FirstInSlot(slot);

   // Try finding the player's currently-equipped weapon.
   while(!baseslot->isDummy())
   {
      if(baseslot->bdObject->weapon->id == wp->id)
      {
         return baseslot->bdObject;
      }
      else
         baseslot = baseslot->bdNext;
   }
   return nullptr;
}
Exemple #15
0
u32 Map::updateLighting(concurrent_map<v3POS, MapBlock*> & a_blocks,
                        std::map<v3POS, MapBlock*> & modified_blocks, unsigned int max_cycle_ms) {
	INodeDefManager *nodemgr = m_gamedef->ndef();

	int ret = 0;
	int loopcount = 0;

	TimeTaker timer("updateLighting");

	// For debugging
	//bool debug=true;
	//u32 count_was = modified_blocks.size();

	//std::unordered_set<v3POS, v3POSHash, v3POSEqual> light_sources;
	//std::unordered_map<v3POS, u8, v3POSHash, v3POSEqual> unlight_from_day, unlight_from_night;
	std::set<v3POS> light_sources;
	std::map<v3POS, u8> unlight_from_day, unlight_from_night;
	unordered_map_v3POS<int> processed;


	int num_bottom_invalid = 0;

	//MutexAutoLock lock2(m_update_lighting_mutex);

#if !ENABLE_THREADS
	auto lock = m_nothread_locker.lock_unique_rec();
#endif

	{
		//TimeTaker t("updateLighting: first stuff");

		u32 end_ms = porting::getTimeMs() + max_cycle_ms;
		for(auto i = a_blocks.begin();
		        i != a_blocks.end(); ++i) {

			auto block = getBlockNoCreateNoEx(i->first);

			for(;;) {
				// Don't bother with dummy blocks.
				if(!block || block->isDummy())
					break;

				auto lock = block->try_lock_unique_rec();
				if (!lock->owns_lock())
					break; // may cause dark areas
				v3POS pos = block->getPos();
				if (processed.count(pos) && processed[pos] <= i->first.Y ) {
					break;
				}
				++loopcount;
				processed[pos] = i->first.Y;
				v3POS posnodes = block->getPosRelative();
				//modified_blocks[pos] = block;

				block->setLightingExpired(true);
				block->lighting_broken = true;

				/*
					Clear all light from block
				*/
				for(s16 z = 0; z < MAP_BLOCKSIZE; z++)
					for(s16 x = 0; x < MAP_BLOCKSIZE; x++)
						for(s16 y = 0; y < MAP_BLOCKSIZE; y++) {
							v3POS p(x, y, z);
							bool is_valid_position;
							MapNode n = block->getNode(p, &is_valid_position);
							if (!is_valid_position) {
								/* This would happen when dealing with a
								   dummy block.
								*/
								infostream << "updateLighting(): InvalidPositionException"
								           << std::endl;
								continue;
							}
							u8 oldlight_day = n.getLight(LIGHTBANK_DAY, nodemgr);
							u8 oldlight_night = n.getLight(LIGHTBANK_NIGHT, nodemgr);
							n.setLight(LIGHTBANK_DAY, 0, nodemgr);
							n.setLight(LIGHTBANK_NIGHT, 0, nodemgr);
							block->setNode(p, n);

							// If node sources light, add to list
							//u8 source = nodemgr->get(n).light_source;
							if(nodemgr->get(n).light_source)
								light_sources.insert(p + posnodes);

							v3POS p_map = p + posnodes;
							// Collect borders for unlighting
							if(x == 0 || x == MAP_BLOCKSIZE - 1
							        || y == 0 || y == MAP_BLOCKSIZE - 1
							        || z == 0 || z == MAP_BLOCKSIZE - 1) {
								if(oldlight_day)
									unlight_from_day[p_map] = oldlight_day;
								if(oldlight_night)
									unlight_from_night[p_map] = oldlight_night;
							}


						}

				lock->unlock();

				bool bottom_valid = propagateSunlight(pos, light_sources);

				if(!bottom_valid)
					num_bottom_invalid++;

				pos.Y--;
				block = getBlockNoCreateNoEx(pos);
			}

			if (porting::getTimeMs() > end_ms) {
				++ret;
				break;
			}
		}

	}

	{
		//TimeTaker timer("updateLighting: unspreadLight");
		unspreadLight(LIGHTBANK_DAY, unlight_from_day, light_sources, modified_blocks);
		unspreadLight(LIGHTBANK_NIGHT, unlight_from_night, light_sources, modified_blocks);
	}

	{
		//TimeTaker timer("updateLighting: spreadLight");
		spreadLight(LIGHTBANK_DAY, light_sources, modified_blocks, porting::getTimeMs() + max_cycle_ms * 10);
		spreadLight(LIGHTBANK_NIGHT, light_sources, modified_blocks, porting::getTimeMs() + max_cycle_ms * 10);
	}

	for (auto & i : processed) {
		a_blocks.erase(i.first);
		MapBlock *block = getBlockNoCreateNoEx(i.first);
		if(!block)
			continue;
		block->setLightingExpired(false);
		block->lighting_broken = false;
	}

	g_profiler->add("Server: light blocks", loopcount);

	return ret;

}
Exemple #16
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 velocit
      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;
               }
               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();
               }
            }
         }

         // Did we miss the target?
         if (missed) {
            // We've detonated ...
            setMode(DETONATED);
            setDetonationResults( DETONATE_DETONATION );

            // because we've just missed the target
            setTargetPlayer(0,false);
            setTargetTrack(0,false);

            // Log the event
            LCreal detRange = trngT;
            if (isMessageEnabled(MSG_INFO)) {
               std::cout << "DETONATE_OTHER rng = " << detRange << std::endl;
            }
            if (getAnyEventLogger() != 0) {
               TabLogger::TabLogEvent* evt = new TabLogger::LogWeaponActivity(2, getLaunchVehicle(), this, getTargetPlayer(), DETONATE_DETONATION, getDetonationRange()); // type 2 for "detonate"
               getAnyEventLogger()->log(evt);
               evt->unref();
            }
         }

      }
   }
}
//----------------------------------------------------------------------------//
void GridLayoutContainer::setGridDimensions(size_t width, size_t height)
{
    // copy the old children list
    ChildList oldChildren = d_children;

    // remove all child windows
    while (getChildCount() != 0)
    {
        Window* wnd = static_cast<Window*>(d_children[0]);
        removeChild(wnd);
    }

    // we simply fill the grid with dummies to ensure everything works smoothly
    // when something is added to the grid, it simply replaces the dummy
    for (size_t i = 0; i < width * height; ++i)
    {
        Window* dummy = createDummy();
        addChild(dummy);
    }

    const size_t oldWidth = d_gridWidth;

    const size_t oldHeight = d_gridHeight;

    const AutoPositioning oldAO = d_autoPositioning;

    d_gridWidth = width;

    d_gridHeight = height;

    // now we have to map oldChildren to new children
    for (size_t y = 0; y < height; ++y)
    {
        for (size_t x = 0; x < width; ++x)
        {
            // we have to skip if we are out of the old grid
            if (x >= oldWidth || y >= oldHeight)
                continue;

            const size_t oldIdx = mapFromGridToIdx(x, y, oldWidth, oldHeight);
            Window* previous = static_cast<Window*>(oldChildren[oldIdx]);

            if (isDummy(previous))
            {
                WindowManager::getSingleton().destroyWindow(previous);
            }
            else
            {
                addChildToPosition(previous, x, y);
            }

            oldChildren[oldIdx] = 0;
        }
    }

    setAutoPositioning(oldAO);
    // oldAOIdx could mean something completely different now!
    // todo: perhaps convert oldAOOdx to new AOIdx?
    setNextAutoPositioningIdx(0);

    // we have to destroy windows that don't fit the new grid if they are set
    // to be destroyed by parent
    for (size_t i = 0; i < oldChildren.size(); ++i)
    {
        if (oldChildren[i] && static_cast<Window*>(oldChildren[i])->isDestroyedByParent())
        {
            WindowManager::getSingleton().destroyWindow(static_cast<Window*>(oldChildren[i]));
        }
    }
}
//----------------------------------------------------------------------------//
void GridLayoutContainer::addChild_impl(Element* element)
{
    Window* wnd = dynamic_cast<Window*>(element);
    
    if (!wnd)
    {
        CEGUI_THROW(InvalidRequestException(
            "GridLayoutContainer can only have Elements of type Window added "
            "as children (Window path: " + getNamePath() + ")."));
    }
    
    if (isDummy(wnd))
    {
        LayoutContainer::addChild_impl(wnd);
    }
    else
    {
        LayoutContainer::addChild_impl(wnd);

        // OK, wnd is already in d_children

        // idx is the future index of the child that's being added
        size_t idx;

        if (d_autoPositioning == AP_Disabled)
        {
            if ((d_nextGridX == std::numeric_limits<size_t>::max()) &&
                (d_nextGridY == std::numeric_limits<size_t>::max()))
            {
                CEGUI_THROW(InvalidRequestException(
                    "Unable to add child without explicit grid position "
                    "because auto positioning is disabled.  Consider using the "
                    "GridLayoutContainer::addChildToPosition functions."));
            }

            idx = mapFromGridToIdx(d_nextGridX, d_nextGridY,
                                   d_gridWidth, d_gridHeight);

            // reset location to sentinel values.
            d_nextGridX = d_nextGridY = std::numeric_limits<size_t>::max();
        }
        else
        {
            idx = translateAPToGridIdx(d_nextAutoPositioningIdx);
            ++d_nextAutoPositioningIdx;
        }

        // we swap the dummy and the added child
        // this essentially places the added child to it's right position and
        // puts the dummy at the end of d_children it will soon get removed from
        std::swap(d_children[idx], d_children[d_children.size() - 1]);

        Window* toBeRemoved = static_cast<Window*>(d_children[d_children.size() - 1]);
        removeChild(toBeRemoved);

        if (toBeRemoved->isDestroyedByParent())
        {
            WindowManager::getSingleton().destroyWindow(toBeRemoved);
        }
    }
}
void Project::save( bool onlyProjectFile )
{
    bool anythingModified = FALSE;

    //  save sources and forms
    if ( !onlyProjectFile ) {

	saveConnections();

	for ( SourceFile *sf = sourcefiles.first(); sf; sf = sourcefiles.next() ) {
	    anythingModified = anythingModified || sf->isModified();
	    if ( !sf->save() )
		return;
	}

	for ( FormFile *ff = formfiles.first(); ff; ff = formfiles.next() ) {
	    anythingModified = anythingModified || ff->isModified();
	    if ( !ff->save() )
		return;
	}
    }

    if ( isDummy() || filename.isEmpty() )
	return;

    if ( !modified ) {
	if ( singleProjectMode() ) {
	    LanguageInterface *iface = MetaDataBase::languageInterface( language() );
	    if ( iface && iface->supports( LanguageInterface::CompressProject ) )
		iface->compressProject( makeAbsolute( filename ), singleProFileName, anythingModified );
	}
 	return;
    }

    QFile f( filename );
    QString original = "";

    // read the existing file
    bool hasPreviousContents = FALSE;
    if ( f.open( IO_ReadOnly ) ) {
	QTextStream ts( &f );
	original = ts.read();
	f.close();
        hasPreviousContents = TRUE;
	remove_contents( original, "{SOURCES+=" ); // ### compatibility with early 3.0 betas
	remove_contents( original, "DBFILE" );
	remove_contents( original, "LANGUAGE" );
	remove_contents( original, "TEMPLATE" );
	removePlatformSettings( original, "CONFIG" );
	removePlatformSettings( original, "DEFINES" );
	removePlatformSettings( original, "LIBS" );
	removePlatformSettings( original, "INCLUDEPATH" );
	removePlatformSettings( original, "SOURCES" );
	removePlatformSettings( original, "HEADERS" );
	remove_multiline_contents( original, "FORMS" );
	remove_multiline_contents( original, "INTERFACES" ); // compatibility
	remove_multiline_contents( original, "IMAGES" );
	for ( QStringList::Iterator it = csList.begin(); it != csList.end(); ++it )
	    remove_contents( original, *it );
    }

    if (!original.isEmpty()) {
	// Removes any new lines at the beginning of the file
	while (original.startsWith("\n"))
	    original.remove(0, 1);
    }

    // the contents of the saved file
    QString contents;

    // template
    contents += "TEMPLATE\t= " + templ + "\n";

    // language
    contents += "LANGUAGE\t= " + lang + "\n";
    contents += "\n";

    // config
    writePlatformSettings( contents, "CONFIG", cfg );
    LanguageInterface *iface = MetaDataBase::languageInterface( lang );
    if ( iface ) {
	QStringList sourceKeys;
	iface->sourceProjectKeys( sourceKeys );
	for ( QStringList::Iterator spit = sourceKeys.begin(); spit != sourceKeys.end(); ++spit )
	    remove_multiline_contents( contents, *spit );
    }

    // libs, defines, includes
    writePlatformSettings( contents, "LIBS", lbs );
    writePlatformSettings( contents, "DEFINES", defs );
    writePlatformSettings( contents, "INCLUDEPATH", inclPath );
    writePlatformSettings( contents, "SOURCES", sources );
    writePlatformSettings( contents, "HEADERS", headers );

    // unix
    if ( !hasPreviousContents ) {
 	contents +=
 	    "unix|os2 {\n"
 	    "  UI_DIR = .ui\n"
 	    "  MOC_DIR = .moc\n"
 	    "  OBJECTS_DIR = .obj\n"
 	    "}\n\n";
    }

    // sources
    if ( !sourcefiles.isEmpty() && iface ) {
	QMap<QString, QStringList> sourceToKey;
	for ( SourceFile *f = sourcefiles.first(); f; f = sourcefiles.next() ) {
	    QString key = iface->projectKeyForExtension( QFileInfo( f->fileName() ).extension() );
	    QStringList lst = sourceToKey[ key ];
	    lst << makeRelative( f->fileName() );
	    sourceToKey.replace( key, lst );
	}

	for ( QMap<QString, QStringList>::Iterator skit = sourceToKey.begin();
	      skit != sourceToKey.end(); ++skit ) {
	    QString part = skit.key() + "\t+= ";
	    QStringList lst = *skit;
	    for ( QStringList::Iterator sit = lst.begin(); sit != lst.end(); ++sit ) {
		part += *sit;
		part += ++sit != lst.end() ? " \\\n\t" : "";
		--sit;
	    }
	    part += "\n\n";
	    contents += part;
	}
    }

    // forms and interfaces
    if ( !formfiles.isEmpty() ) {
	contents += "FORMS\t= ";
	for ( QPtrListIterator<FormFile> fit = formfiles; fit.current(); ++fit ) {
	    contents += fit.current()->fileName() +
		 (fit != formfiles.last() ? " \\\n\t" : "");
	}
	contents += "\n\n";
    }

    // images
     if ( !pixCollection->isEmpty() ) {
	contents += "IMAGES\t= ";
	QValueList<PixmapCollection::Pixmap> pixmaps = pixCollection->pixmaps();
	for ( QValueList<PixmapCollection::Pixmap>::Iterator it = pixmaps.begin();
	      it != pixmaps.end(); ++it ) {
		  contents += makeRelative( (*it).absname );
		  contents += ++it != pixmaps.end() ? " \\\n\t" : "";
		  --it;
	}
	contents += "\n\n";
    }

    // database
    if ( !dbFile.isEmpty() )
	contents += "DBFILE\t= " + dbFile + "\n";

    // custom settings
    for ( QStringList::Iterator it = csList.begin(); it != csList.end(); ++it ) {
	QString val = *customSettings.find( *it );
	if ( !val.isEmpty() )
	    contents += *it + "\t= " + val + "\n";
    }

    if ( !f.open( IO_WriteOnly | IO_Translate ) ) {
	QMessageBox::warning( messageBoxParent(),
			      "Save Project Failed", "Couldn't write project file " + filename );
	return;
    }

    QTextStream os( &f );
    os << contents;
    if (hasPreviousContents)
        os << original;

    f.close();

    setModified( FALSE );

    if ( singleProjectMode() ) {
	LanguageInterface *iface = MetaDataBase::languageInterface( language() );
	if ( iface && iface->supports( LanguageInterface::CompressProject ) )
	    iface->compressProject( makeAbsolute( filename ), singleProFileName, TRUE );
    }
}
Exemple #20
0
//------------------------------------------------------------------------------
// mapPlayerList2ModelTable() - Map the player list to the model table
//
//  model states are:
//     INACTIVE     -- unused model entry
//     ACTIVE       -- player is alive and in-range
//     DEAD         -- player is dead or destroyed
//     OUT_OF_RANGE -- player is alive but out of range
//
//  Note: this routines will set model entries to DEAD and OUT_OF_RANGE, but the
//  derived class should handle the visual system unique termination sequences and
//  clear the model entry.
//------------------------------------------------------------------------------
void Otw::mapPlayerList2ModelTable()
{
   // ---
   // Check for reset
   // ---
   if (isResetInProgress()) {
      // Set all active models as Out-Of-Range so that sendOwnshipAndModels() can remove them
      for (unsigned int i = 0; i < getModelTableSize(); i++) {
         modelTbl[i]->setState( OtwModel::OUT_OF_RANGE );
      }
      return;
   }

   // ---
   // Remove all inactive, dead or out-of-range models
   //   -- These states were issued last pass, so the OTW system
   //       specific software should have handled them by now.
   //   -- As models are removed, the table above the model is shifted down.
   //   -- We're also clearing the model's 'checked' flag
   // ---
   for (int i = getModelTableSize(); i > 0; --i) {
      if ( modelTbl[i-1]->isState(OtwModel::CLEARED) ) {
         // Deleting this model
         //std::cout << "Otw::mapPlayerList2ModelTable() cleanup: model = " << modelTbl[i] << std::endl;
         removeModelFromList( (i-1), MODEL_TABLE);
      }
   }
   for (unsigned int i = 0; i < getModelTableSize(); i++) {
      modelTbl[i]->setCheckedFlag(false);
   }

   if (playerList != nullptr) {
      // We must have a player list ...

      // ---
      // Find players that are alive and within range of the visual system ...
      // ---
      base::List::Item* item = playerList->getFirstItem();
      while (item != nullptr) {

         // Get a pointer to the player, 'p'
         const auto pair = static_cast<base::Pair*>(item->getValue());
         const auto p = static_cast<models::Player*>(pair->object());

         bool dummy = false;
         const auto wpn = dynamic_cast<const models::AbstractWeapon*>( p );
         if (wpn != nullptr) dummy = wpn->isDummy();

         if ( p != getOwnship() && !dummy ) {

            // Find the player's model entry (if any)
            OtwModel* model = findModel(p, MODEL_TABLE);

            // Check if in-range
            bool inRange = computeRangeToPlayer(p) <= maxRange;

            // Check if this player is alive and within range.
            if (p->isActive() && inRange) {
               // When alive and in range ...
               if (model != nullptr) {
                  // a) and it already has a model entry: make sure it's active ...
                  model->setState( OtwModel::ACTIVE );
               }
               else {
                  // b) and it doesn't have a model entry (new, in-range player) ...
                  model = newModelEntry(p);
               }
            }
            else if (p->isDead() && inRange) {
               // When player isn't alive and it had a model entry
               if (model != nullptr) {
                  // set state to dead
                  model->setState( OtwModel::DEAD );
               }
            }
            else {
               // When player is out-of-range and it had a model entry
               if (model != nullptr) {
                  // set state to out-of-range
                  model->setState( OtwModel::OUT_OF_RANGE );
               }
            }
            if (model != nullptr) model->setCheckedFlag(true);

         }

         item = item->getNext(); // Next player
      }

   }

   // ---
   // Any models not checked needs to be removed
   // ---
   for (unsigned int i = 0; i < getModelTableSize(); i++) {
      if ( modelTbl[i]->isNotChecked() ) {
         // Request removal;
         // (note: the OTW system specific code now has one frame to cleanup its own code
         //  before the model is dropped from the output list next frame -- see above)
         modelTbl[i]->setState( OtwModel::OUT_OF_RANGE );
      }
   }

}