Ejemplo n.º 1
0
void Grid2dUtility::get5Neighbors(std::vector<int>& neighbors, const Vec2i& p) const
{
    neighbors.clear();
    if(!isInside(p))
        return;

    Vec2i neighbor;

    neighbor = p;
    if(isInside(neighbor))
        neighbors.push_back(cellId(neighbor));

    neighbor = p + Vec2i(1,0);
    if(isInside(neighbor))
        neighbors.push_back(cellId(neighbor));

    neighbor = p + Vec2i(-1,0);
    if(isInside(neighbor))
        neighbors.push_back(cellId(neighbor));

    neighbor = p + Vec2i(0,1);
    if(isInside(neighbor))
        neighbors.push_back(cellId(neighbor));

    neighbor = p + Vec2i(0,-1);
    if(isInside(neighbor))
        neighbors.push_back(cellId(neighbor));
}
Ejemplo n.º 2
0
std::pair<TRasterP, TCacheResource::CellData *> TCacheResource::touch(const PointLess &cellIndex)
{
	std::string cellId(getCellCacheId(cellIndex.x, cellIndex.y));

	std::map<PointLess, CellData>::iterator it = m_cellDatas.find(cellIndex);
	if (it != m_cellDatas.end()) {
		//Retrieve the raster from image cache
		TImageP img(TImageCache::instance()->get(cellId, true));
		if (img)
			return std::make_pair(getRaster(img), &it->second);
	}

	it = m_cellDatas.insert(std::make_pair(cellIndex, CellData())).first;

	//Then, attempt retrieval from back resource
	TRasterP ras(load(cellIndex));
	if (ras) {
		TImageCache::instance()->add(cellId, TRasterImageP(ras));
		return std::make_pair(ras, &it->second);
	}

	//Else, create it
	return std::make_pair(
		createCellRaster(m_tileType, cellId), //increases m_cellsCount too
		&it->second);
}
Ejemplo n.º 3
0
void GridUtility::get27Neighbors(std::vector<int>& neighbors, const Vec3i& p, const int radius) const
{
    if(!isInside(p))
    {
        neighbors.clear();
        return;
    }

    int kmin = std::max(p[2]-radius,0);
    int kmax = std::min(p[2]+radius,dimension[2]-1);
    int jmin = std::max(p[1]-radius,0);
    int jmax = std::min(p[1]+radius,dimension[1]-1);
    int imin = std::max(p[0]-radius,0);
    int imax = std::min(p[0]+radius,dimension[0]-1);
    int size = (kmax-kmin+1)*(jmax-jmin+1)*(imax-imin+1);
    neighbors.resize(size);
    int counter = 0;

    for(int k = kmin; k<= kmax; ++k )
    {
        for(int j = jmin; j<= jmax; ++j )
        {
            for(int i = imin; i<= imax; ++i )
            {
                neighbors[counter] = cellId(i,j,k);
                counter++;
            }
        }
    }
}
Ejemplo n.º 4
0
int Grid2dUtility::neighborPixelId(int pixelId, int neighborId) const
{
    Vec2i neighborCoord = gridCoord(pixelId);

    switch( neighborId )
    {
        case 0 :
            neighborCoord += Vec2i(0,-1);
            break;
        case 1 :
            neighborCoord += Vec2i(1,0);
            break;
        case 2 :
            neighborCoord += Vec2i(0,1);
            break;
        case 3 :
            neighborCoord += Vec2i(-1,0);
            break;
        default :
            break;
    }

    if ( isInside(neighborCoord) )
        return cellId( neighborCoord );
    else
        return -1;
}
Ejemplo n.º 5
0
void Grid2dUtility::get9Neighbors(std::vector<int>& neighbors, const Vec2i& p, const int radius)
{
    neighbors.clear();
    if(!isInside(p))
        return;

        for(int j = std::max(p[1]-radius,0); j<= std::min(p[1]+radius,dimension[1]-1); ++j )
        {
            for(int i = std::max(p[0]-radius,0); i<= std::min(p[0]+radius,dimension[0]-1); ++i )
            {
                neighbors.push_back(cellId(i,j));
            }
        }
}
Ejemplo n.º 6
0
Id ReadCell::startGraftCell( const string& cellPath )
{
	/*
	 * If path exists, return with error. This will also catch the case where
	 * cellPath is "/", and we will not have to check for this separately
	 * later.
	 */
	Id cellId( cellPath );
	if ( cellId.path() == cellPath ) {
		cerr << "Warning: ReadCell: cell '" << cellPath << "' already exists.\n";
		cerr << "File: " << fileName_ << " Line: " << lineNum_ << endl;
		return Id();
	}
	
        ObjId parentObjId;
	string cellName;
	string::size_type pos_1 = cellPath.find_first_of( "/" );
	string::size_type pos_2 = cellPath.find_last_of( "/" );
	
	if ( pos_1 != 0 ) {
		cerr << "Error: ReadCell: *start_cell should be given absolute path.\n";
		cerr << "File: " << fileName_ << " Line: " << lineNum_ << endl;
		return Id();
	}
	
	if ( pos_2 == 0 ) {
            parentObjId = ObjId("/");
		cellName = cellPath.substr( 1 );
	} else {
		string parentPath = cellPath.substr( 0, pos_2  );
		parentObjId = ObjId( parentPath );
		if ( parentObjId.bad() ) {
			cerr << "Error: ReadCell: cell path '" << cellPath
				<< "' not found.\n";
			cerr << "File: " << fileName_ << " Line: " << lineNum_ << endl;
			return Id();
		}
		
		cellName = cellPath.substr( pos_2 + 1 );
	}
	
	unsigned int size = 1;
	return shell_->doCreate( "Compartment", parentObjId, cellName, size, MooseGlobal );
}
Ejemplo n.º 7
0
/*!
    Update the registration \a state and notify all interested clients
    if it is different than the previous value.  The locationAreaCode()
    and cellId() will be set to -1.

    \sa QGprsNetworkRegistration::registrationState()
    \sa QGprsNetworkRegistration::registrationStateChanged()
*/
void QGprsNetworkRegistrationServer::updateRegistrationState
        ( QTelephony::RegistrationState state )
{
    if ( locationAreaCode() != -1 || cellId() != -1 ) {
        if ( state != registrationState() ) {
            // Update everything.
            setValue( "state", (int)state, Delayed );
            setValue( "locationAreaCode", -1, Delayed );
            setValue( "cellId", -1 );
            emit registrationStateChanged();
            emit locationChanged();
        } else {
            // Update only the location.
            setValue( "locationAreaCode", -1, Delayed );
            setValue( "cellId", -1 );
            emit locationChanged();
        }
    } else if ( state != registrationState() ) {
        // Update only registration.
        setValue( "state", (int)state );
        emit registrationStateChanged();
    }
}
Ejemplo n.º 8
0
QVariant Cell::parseMember(const QString &formula, SpreadSheet *widget) const
{
    int fOp = firstOperatorPosition(formula);
    if (fOp == -1)
        fOp = formula.length();
    QChar first = formula.at(0);
    
    QRegExp importedData("([\\w\\s]+:[A-Z][1-9][0-9]*)");
    QRegExp cellId("([A-Z][1-9][0-9]*)");
    
    //paranteza
    if (first=='(')
    {
        int end = 0;
        int open_p_count = 0;
        int closed_p_count = 0;
        for (int c=0; c<formula.length(); c++)
        {
            if (formula.at(c) == '(')
                open_p_count++;
            else if (formula.at(c) == ')')
                closed_p_count++;
            if (open_p_count == closed_p_count)
            {
                end = c;
                break;
            }
        }
        return computeFormula(formula.mid(1,end-1), widget);
    }
    //numar 0 sau 0.0
    else if (first.isDigit())
    {
        QString s = formula.left(fOp);
        if (s.count('.') <= 1)
        {
            bool ok;
            double x = s.toDouble(&ok);
            if (ok)
                return x;
        }
        emit invalidFormula(QString("Invalid number or number format in %1").arg(s));
        return "#####";
    }
    //tabela:identificator
    else if (formula.indexOf(importedData) == 0)
    {
        int idx = 0;
        QHash<QString,QString> matches = QHash<QString,QString>();
        while ((idx = formula.indexOf(importedData, idx)) != -1)
        {
            QString match = formula.mid(idx, importedData.matchedLength());
            int delim = match.indexOf(':');
            QString table = match.left(delim);
            QString id = match.mid(delim+1);
            matches.insertMulti(table, id);
            idx += importedData.matchedLength();
        }
        QString result = widget->getLinkData(formula, matches);
        if (isValidFormula(result))
            return display(result);
        else
            return result;
    }
    //celula A2
    else if (cellId.exactMatch(formula))
    {
        QVariant cellVal = getCellValue(formula,widget);
        if (cellVal == "#####")
            emit invalidFormula(QString("Invalid cell data in %1").arg(formula));
        return cellVal;
    }
    //functie nume_functie(A1;A2;A3)
    else if (first.isLower())
    {
        QStringList simple_function_names;
        QStringList cond_function_names;
        QStringList parameters;
        simple_function_names << "sum" << "avg" << "count";
        cond_function_names << "if" << "countif";
        QString s = formula.left(fOp);

        QString params = s.mid(s.lastIndexOf('(')+1,
                               s.indexOf(')')-s.lastIndexOf('(')-1);
        if (s.count('(') == s.count(')'))
            parameters = params.split(';');
        else
        {
            emit invalidFormula(QString("Invalid paranthesis number ").append(s));
            return "#####";
        }
        s = formula.left(formula.indexOf('('));
        if (simple_function_names.contains(s))
        {
            QVariantList values;
            QListIterator<QString> it(parameters);
            while (it.hasNext())
            {
                QString str = it.next();
                QVariant val = parseMember(str, widget);
                if (val != "#####")
                    values.append(val);
            }

            if (s == "sum")
            {
                double tmp = 0;
                bool ok = true;
                QListIterator<QVariant> valIt(values);
                while (valIt.hasNext())
                {
                    QVariant aux = valIt.next();
                    tmp += aux.toDouble(&ok);
                    if (!ok)
                    {
                        emit invalidFormula(QString("Not a number: ").append(aux.toString()));
                        return "#####";
                    }
                }
                return tmp;
            }
            else if (s == "avg")
            {
                double tmp = 0;
                bool ok = true;
                QListIterator<QVariant> valIt(values);
                while (valIt.hasNext())
                {
                    QVariant aux = valIt.next();
                    tmp += aux.toDouble(&ok);
                    if (!ok)
                    {
                        emit invalidFormula(QString("Not a number: ").append(aux.toString()));
                        return "#####";
                    }
                }
                tmp /= parameters.length();
                return tmp;
            }
            else if (s == "count")
            {
                return values.length();
            }
        }
        else if (cond_function_names.contains(s))
        {
            int param_no = parameters.length();
            if (param_no < 2)
            {
                emit invalidFormula(QString("Invalid parameter number: %1").arg(param_no));
                return "#####";
            }
            
            if (s == "if")
            {
                //if(A1<5;"Picat";n)
                //if(A1<5;4)
                QRegExp pattern("^(([\\w\\s]+:)?[A-Z][1-9][0-9]*"
                                "(<|<=|>|>=|<>|=)"
                                "((([\\w\\s]+:)?[A-Z][1-9][0-9]*)|(\\d+(\\.\\d+)?)))$");
                QString condition = parameters.at(0);
                if (pattern.exactMatch(condition) && param_no <= 3)
                {
                    int length = 1;
                    int opPos = condition.indexOf(QRegExp("(<|>|=)"));
                    if (condition.indexOf(QRegExp("(<=|>=|<>)")) > -1)
                        length = 2;
                    QString op = condition.mid(opPos,length);
                    bool ok1, ok2;
                    double firstOperand = parseMember(condition.left(opPos), widget).toDouble(&ok1);
                    double secondOperand = parseMember(condition.mid(opPos+length), widget).toDouble(&ok2);
                    if (!ok1 || !ok2)
                    {
                        emit invalidFormula(QString("Invalid condition parameters: %1").arg(condition));
                        return "#####";
                    }
                    if (param_no == 2)
                        return compareMembers(param_no, op,
                                              firstOperand, secondOperand,
                                              parameters.at(1), "#####");
                    else if (param_no == 3)
                        return compareMembers(param_no, op,
                                              firstOperand, secondOperand,
                                              parameters.at(1), parameters.at(2));
                }
                else
                {
                    emit invalidFormula(QString("Invalid formula syntax: ").append(condition));
                    return "#####";
                }
            }
            else if (s == "countif")
            {
                //countif(A1;A2...An;>5)
                if (param_no > 2)
                {
                    int count = 0;
                    int length = 1;
                    QString condition = parameters.last();
                    int opPos = condition.indexOf(QRegExp("(<|>|=)"));
                    if (condition.indexOf(QRegExp("(<=|>=|<>)")) > -1)
                        length = 2;
                    if (opPos == -1)
                    {
                        emit invalidFormula(QString("Invalid condition syntax: ").append(condition));
                        return "#####";
                    } 
                    QString op = condition.mid(opPos,length);
                    bool ok;
                    double firstOperand;
                    double secondOperand = parseMember(condition.mid(opPos+length), widget).toDouble(&ok);
                    if (!ok)
                    {
                        emit invalidFormula(QString("Invalid second operand: %1").
                                            arg(condition.mid(opPos+length)));
                        return "#####";
                    }
                    for (int i=0; i<param_no-1; i++)
                    {
                        firstOperand = parseMember(parameters.at(i), widget).toDouble(&ok);
                        if (!ok)
                        {
                            emit invalidFormula(QString("Invalid operand: %1").
                                                arg(parameters.at(i)));
                            return "#####";
                        }
                        if (compareMembers(op, firstOperand, secondOperand))
                            count++;
                    }
                    return count;
                }
            }
        }
        else
        {
            emit invalidFormula("Invalid formula");
            return "#####";
        }
    }
    return formula;
}
Ejemplo n.º 9
0
int Grid3dUtility::cellId(const Vec3f& v) const
{
    Vec3i gridCoord = worldToGrid(v);
    return cellId(gridCoord);
}
Ejemplo n.º 10
0
int Grid2dUtility::cellId(const Vec2r& v) const
{
    Vec2i gridCoord = worldToGrid(v);
    return cellId(gridCoord);
}
Ejemplo n.º 11
0
void CharacterCreationTracker::handleCreateNewCharacter(const ConnectionCreateCharacter &msg)
{
	// - Check whether a creation request is already active for this account
	CreationsType::iterator creationRecord = m_creations.find(msg.getStationId());
	if (creationRecord != m_creations.end())
	{
		if (ServerClock::getInstance().getGameTimeSeconds() > (creationRecord->second->m_creationTime + ConfigCentralServer::getCharacterCreationTimeout()))
		{
			LOG("TraceCharacterCreation", ("%d allowing character creation because previous one timed out", msg.getStationId()));
			DEBUG_REPORT_LOG(true,("Allowing character creation for account %li because previous one timed out.\n",msg.getStationId()));
			unlockAccount(msg.getStationId());
			creationRecord = m_creations.end();
		}
		else
		{
			LOG("TraceCharacterCreation", ("%d refusing character creation because one is already in progress", msg.getStationId()));
			DEBUG_REPORT_LOG(true,("Refusing character creation for account %li because one was already in progress.\n",msg.getStationId()));
			ConnectionCreateCharacterFailed f(msg.getStationId(), msg.getCharacterName(), NameErrors::nameDeclinedRetry, FormattedString<2048>().sprintf("%lu refusing character creation because one is already in progress", msg.getStationId())); //lint !e40 // undeclared identifier nameDeclinedEntry
			CentralServer::getInstance().sendToConnectionServerForAccount(msg.getStationId(), f, true);
			return;
		}
	}

	// - Check whether they are creating characters too rapidly
	// Note that this locks only when creation succeeds.  Failing to create a lot of characters in a row does not lock the account.
	FastCreationLockType::iterator fcl = m_fastCreationLock.find(msg.getStationId());
	if (fcl != m_fastCreationLock.end())
	{
		if (!msg.getNoRateLimit() && ((Clock::timeSeconds() - fcl->second) < (msg.getIsForCharacterTransfer() ? static_cast<uint32>(ConfigCentralServer::getCharacterCtsCreationRateLimitSeconds()) : static_cast<uint32>(ConfigCentralServer::getCharacterCreationRateLimitSeconds()))))
		{
			LOG("TraceCharacterCreation", ("%d refusing character creation because not enough time has passed since the previous one", msg.getStationId()));
			DEBUG_REPORT_LOG(true,("Refusing character creation for account %li because not enough time has passed since the previous one\n",msg.getStationId()));
			ConnectionCreateCharacterFailed f(msg.getStationId(), msg.getCharacterName(), NameErrors::nameDeclinedTooFast, FormattedString<2048>().sprintf("%lu refusing character creation because not enough time has passed since the previous one", msg.getStationId()));
			CentralServer::getInstance().sendToConnectionServerForAccount(msg.getStationId(), f, true);
			return;
		}
	}
	
	if (creationRecord == m_creations.end())
		creationRecord = m_creations.insert(std::make_pair<StationId,CreationRecord*>(msg.getStationId(),new CreationRecord)).first;

	// - determine starting location
	static std::string tutorialPlanetName("tutorial");
	std::string planetName;
	Vector coordinates(0.0f,0.0f,0.0f);
	NetworkId cellId(NetworkId::cms_invalid);
	bool useNewbieTutorial = (ConfigCentralServer::getNewbieTutorialEnabled() && msg.getUseNewbieTutorial() && ! msg.getIsForCharacterTransfer());
	if (useNewbieTutorial)
		planetName = tutorialPlanetName;
	else
	{
		if (!getStartLocation(msg.getStartingLocation(), planetName, coordinates, cellId))
		{
			// bad starting location
			LOG("TraceCharacterCreation", ("%d bad starting location (%s)", msg.getStationId(), msg.getStartingLocation().c_str()));
			ConnectionCreateCharacterFailed cccf(msg.getStationId(), msg.getCharacterName(), SharedStringIds::character_create_failed_bad_location, FormattedString<2048>().sprintf("%lu bad starting location (%s)", msg.getStationId(), msg.getStartingLocation().c_str()));
			CentralServer::getInstance().sendToConnectionServerForAccount(msg.getStationId(), cccf, true);
			unlockAccount(msg.getStationId());
			return;
		}
	}

	// - send request to game server
	creationRecord->second->m_gameCreationRequest = new CentralCreateCharacter(
		msg.getStationId(),
		msg.getCharacterName(),
		msg.getTemplateName(),
		msg.getScaleFactor(),
		planetName,
		coordinates,
		cellId,
		msg.getAppearanceData(),
		msg.getHairTemplateName(),
		msg.getHairAppearanceData(),
		msg.getProfession(),
		msg.getBiography(),
		useNewbieTutorial,
		msg.getSkillTemplate(),
		msg.getWorkingSkill(),
		msg.getJedi(),
		msg.getGameFeatures());
	uint32 gameServerId = CentralServer::getInstance().sendToRandomGameServer(*(creationRecord->second->m_gameCreationRequest));
	if (gameServerId == 0)
	{
		DEBUG_REPORT_LOG(true, ("Could not find a game server for character creation, starting a tutorial server\n"));
		LOG("TraceCharacterCreation", ("%d waiting for game server", msg.getStationId()));
		CentralServer::getInstance().startPlanetServer(CentralServer::getInstance().getHostForScene(tutorialPlanetName), tutorialPlanetName, 0);
		creationRecord->second->m_stage = CreationRecord::S_queuedForGameServer;
		return;
	}

	LOG("TraceCharacterCreation", ("%d sending CentralCreateCharacter(%s) to game server %lu", msg.getStationId(), Unicode::wideToNarrow(msg.getCharacterName()).c_str(), gameServerId));
	creationRecord->second->m_stage = CreationRecord::S_sentToGameServer;
	creationRecord->second->m_gameServerId = gameServerId;
}
Ejemplo n.º 12
0
	void move( cUObject* object, const Coord& newPos )
	{
		remove( object );
		cell( cellId( newPos.x, newPos.y ) ).add( object );
	}
Ejemplo n.º 13
0
	//! add() never fails, no need to return a bool. It doesn't validate the
	//! object's position, as that can be more effectively done by the caller.
	void add( cUObject* object, const Coord &pos )
	{
		cell( cellId( pos.x, pos.y ) ).add( object );
	}
Ejemplo n.º 14
0
	//! add() never fails, no need to return a bool. It doesn't validate the
	//! object's position, as that can be more effectively done by the caller.
	void add( cUObject* object )
	{
		const Coord &pos = object->pos();
		cell( cellId( pos.x, pos.y ) ).add( object );
	}