Example #1
0
ALERROR CTopologyNode::ParseCriteriaInt (const CString &sCriteria, SCriteria *retCrit)

//	ParseCriteriaInt
//
//	Parses a string criteria

	{
	char *pPos = sCriteria.GetASCIIZPointer();
	while (*pPos != '\0')
		{
		switch (*pPos)
			{
			case '+':
			case '-':
				{
				bool bRequired = (*pPos == '+');
				CString sParam = ::ParseCriteriaParam(&pPos, false);
				if (bRequired)
					retCrit->AttribsRequired.Insert(sParam);
				else
					retCrit->AttribsNotAllowed.Insert(sParam);
				break;
				}
			}

		pPos++;
		}

	return NOERROR;
	}
Example #2
0
void CG16bitFont::DrawText (CG16bitImage &Dest, 
							int x, 
							int y, 
							WORD wColor, 
							DWORD byOpacity,
							const CString &sText,
							DWORD dwFlags,
							int *retx) const

//	DrawText
//
//	Draws a line of text on the given image

	{
	char *pPos = sText.GetASCIIZPointer();
	char *pEndPos = pPos + sText.GetLength();
	int xPos = x;

	if (dwFlags & AlignCenter)
		{
		int cxWidth = MeasureText(sText);
		xPos -= cxWidth / 2;
		}
	else if (dwFlags & AlignRight)
		{
		int cxWidth = MeasureText(sText);
		xPos -= cxWidth;
		}

	bool bInQuotes = false;
	while (pPos < pEndPos)
		{
		//	Get metrics

		int iIndex = (int)(BYTE)(*pPos) - g_iStartChar;
		iIndex = max(0, iIndex);

		CharMetrics *pMetrics = (CharMetrics *)m_Metrics.GetStruct(iIndex);

		//	Paint

		Dest.FillMask(0,
				iIndex * m_cyHeight,
				pMetrics->cxWidth,
				m_cyHeight,
				m_FontImage,
				wColor,
				xPos,
				y,
				(BYTE)byOpacity);

		pPos++;
		xPos += pMetrics->cxAdvance;
		}
	
	if (retx)
		*retx = xPos;
	}
Example #3
0
ALERROR IEffectPainter::ValidateClass (SLoadCtx &Ctx, const CString &sOriginalClass)

//	ValidateClass
//
//	Reads the class string. If the class does not match the current painter,
//	we read the old data and return ERR_FAIL.

	{
	if (Ctx.dwVersion >= 40)
		{
		CString sClass;
		sClass.ReadFromStream(Ctx.pStream);

		//	If the original class doesn't match the current one, then it means
		//	that the design changed. In that case, we load the painter using the
		//	old class.

		if (!strEquals(sClass, sOriginalClass))
			{
			//	If sClass is blank, then it means that the original did not have
			//	an effect painter (but the current design does)

			if (!sClass.IsBlank())
				{
				//	Get the original creator

				CEffectCreator *pOriginalCreator;
				if (CEffectCreator::CreateFromTag(sClass, &pOriginalCreator) != NOERROR)
					{
					kernelDebugLogMessage("Unable to find original effect creator: %s", sClass.GetASCIIZPointer());
					return ERR_FAIL;
					}

				//	Load the original painter

				IEffectPainter *pOriginalPainter = pOriginalCreator->CreatePainter();
				pOriginalPainter->ReadFromStream(Ctx);

				//	Discard

				pOriginalPainter->Delete();
				delete pOriginalCreator;
				}

			//	Done

			return ERR_FAIL;
			}
		}

	return NOERROR;
	}
Example #4
0
bool isAllNumbers (const CString &sWord)
{
    char *pPos = sWord.GetASCIIZPointer();
    while (*pPos != '\0')
    {
        if (*pPos < '0' || *pPos > '9')
            return false;

        pPos++;
    }

    return true;
}
Example #5
0
void AddText (TraverseCtx &Ctx, const CString &sText)
{
    enum States
    {
        stateInText,
        stateInDelimeter,
        stateDone,
    };

    //	Parse the text into words

    char *pPos = sText.GetASCIIZPointer();
    char *pStart = pPos;
    int iState = stateInText;
    CString sWord;

    while (iState != stateDone)
    {
        bool bText = strIsAlphaNumeric(pPos);

        switch (iState)
        {
        case stateInText:
        {
            if (!bText)
            {
                AddWord(Ctx, CString(pStart, pPos - pStart));
                iState = stateInDelimeter;
            }
            break;
        }

        case stateInDelimeter:
        {
            if (bText)
            {
                pStart = pPos;
                iState = stateInText;
            }
            break;
        }
        }

        //	Next

        if (*pPos == '\0')
            iState = stateDone;
        else
            pPos++;
    }
}
Example #6
0
ALERROR CTopologyNode::AddStargate (const CString &sGateID, const CString &sDestNodeID, const CString &sDestGateID)

//	AddStargate
//
//	Adds a new stargate to the topology

	{
	//	Get the destination node

	CTopologyNode *pDestNode = g_pUniverse->FindTopologyNode(sDestNodeID);
	if (pDestNode == NULL)
		{
		kernelDebugLogMessage("Unable to find destination node: %s", sDestNodeID.GetASCIIZPointer());
		return ERR_FAIL;
		}

	//	Look for the destination stargate

	CString sReturnNodeID;
	CString sReturnEntryPoint;
	if (!pDestNode->FindStargate(sDestGateID, &sReturnNodeID, &sReturnEntryPoint))
		{
		kernelDebugLogMessage("Unable to find destination stargate: %s", sDestGateID.GetASCIIZPointer());
		return ERR_FAIL;
		}

	//	Add the gate

	AddGateInt(sGateID, sDestNodeID, sDestGateID);

	//	See if we need to fix up the return gate

	if (strEquals(sReturnNodeID, PREV_DEST))
		pDestNode->SetStargateDest(sDestGateID, GetID(), sGateID);

	return NOERROR;
	}
Example #7
0
ALERROR CG16bitFont::Create (const CString &sTypeface, int iSize, bool bBold, bool bItalic, bool bUnderline)

//	Create
//
//	Creates a basic font

	{
	ALERROR error;

	DWORD dwQuality;
	if (Absolute(iSize) <= 10)
		dwQuality = ANTIALIASED_QUALITY;
	else
		dwQuality = PROOF_QUALITY;

	HFONT hFont = ::CreateFont(iSize,
			0,
			0,
			0,
			(bBold ? FW_BOLD : FW_NORMAL),
			(bItalic ? TRUE : FALSE),
			(bUnderline ? TRUE : FALSE),
			FALSE,
			ANSI_CHARSET,
			OUT_TT_ONLY_PRECIS,
			CLIP_DEFAULT_PRECIS,
			dwQuality,
			FF_DONTCARE,
			sTypeface.GetASCIIZPointer());
	error = CreateFromFont(hFont);
	DeleteObject(hFont);

	//	HACK: For now we remember the styles from what was passed in
	//	(In the future, these should be set inside CreateFromFont from
	//	the actual font selected).

	m_bBold = bBold;
	m_bItalic = bItalic;
	m_bUnderline = bUnderline;

	return error;
	}
Example #8
0
CString CNPServer::ComposeCmdError (ClientCtx *pClient, int iCmd, ALERROR error)

//	ComposeCmdError
//
//	Composes a RES_CMD_FAIL message with an error code

	{
	CString sError;

	//	Get the error string

	switch (error)
		{
		case NPERROR_FLEET_IN_TRANSIT:
			sError = CONSTLIT("Fleet is in transit");
			break;

		case NPERROR_FLEET_NO_HYPERDRIVE:
			sError = CONSTLIT("Fleet cannot enter hyperspace");
			break;

		default:
			sError = CONSTLIT("Unexpected server error.");
		}

	//	Log the error

	char szBuffer[1024];
	wsprintf(szBuffer, "[%d] CMDFAIL(%d): %s: %d", pClient->dwClientID, iCmd, sError.GetASCIIZPointer(), error);
	Log(szBuffer);

	//	Send reply

	CDataPackStruct Reply;
	Reply.AppendInteger(RES_CMD_FAIL);
	Reply.AppendInteger(iCmd);
	Reply.AppendString(sError);

	return Reply.SerializeToString();
	}
Example #9
0
ALERROR CTopologyNode::ParsePosition (const CString &sValue, int *retx, int *rety)

//	ParsePosition
//
//	Parse a node position (x,y)

	{
	//	Pre-init

	*retx = 0;
	*rety = 0;

	//	Parse

	char *pPos = sValue.GetASCIIZPointer();

	bool bInvalid;
	*retx = ::strParseInt(pPos, 0, &pPos, &bInvalid);
	if (bInvalid)
		return ERR_FAIL;

	//	Skip whitespace

	while (::strIsWhitespace(pPos))
		pPos++;

	//	Skip delimeter

	if (*pPos != ',')
		return ERR_FAIL;
	pPos++;

	//	Next value

	*rety = ::strParseInt(pPos, 0, &pPos, &bInvalid);
	if (bInvalid)
		return ERR_FAIL;

	return NOERROR;
	}
Example #10
0
CString CNPServer::ComposeCmdFail (ClientCtx *pClient, int iCmd, CString sMessage)

//	ComposeCmdFail
//
//	Composes a RES_CMD_FAIL message

	{
	//	Report as error

	char szBuffer[1024];
	wsprintf(szBuffer, "[%d] CMDFAIL(%d): %s", pClient->dwClientID, iCmd, sMessage.GetASCIIZPointer());
	Log(szBuffer);

	//	Send reply

	CDataPackStruct Reply;
	Reply.AppendInteger(RES_CMD_FAIL);
	Reply.AppendInteger(iCmd);
	Reply.AppendString(sMessage);

	return Reply.SerializeToString();
	}
Example #11
0
CString CNPServer::CmdCreateUniverse (ClientCtx *pClient, const CDataPackStruct &Data)
	{
	ALERROR error;
	CString sReply;

	//	Get parameters

	CString sPassword = Data.GetStringItem(1);
	CString sTemplate = LITERAL("NPUniverse.xml");
	Log("[%d] CreateUniverse using '%s'", pClient->dwClientID, sTemplate.GetASCIIZPointer());

	Lock();

	//	If the universe already exists then we're done

	if (m_pUniv != NULL)
		{
		Unlock();
		return ComposeCmdFail(pClient, CMD_CREATE_UNIVERSE, LITERAL("The Universe already exists."));
		}

	//	Create the universe

	CString sError;
	if (error = CNPUniverse::CreateUniverse(sTemplate, &m_pUniv, &sError))
		{
		Unlock();
		return ComposeCmdFail(pClient, CMD_CREATE_UNIVERSE, sError);
		}

	//	Initialize some stuff

	m_sOverlordPassword = sPassword;
	m_dwGameUNID = 666;
	m_bOpenAccess = true;

	Unlock();
	return ComposeCmdSuccess(pClient, CMD_CREATE_UNIVERSE);
	}
Example #12
0
void CTextFileLog::LogOutput (DWORD dwFlags, const CString &sLine)

//	LogOutput
//
//	Output a line to the log

	{
	DWORD dwWritten;

	ASSERT(m_hFile);

	//	Write the time date

	if (dwFlags & ILOG_FLAG_TIMEDATE)
		{
		char szBuffer[1024];
		SYSTEMTIME time;

		GetLocalTime(&time);
		int iLen = wsprintf(szBuffer, "%02d/%02d/%04d %02d:%02d:%02d\t",
				time.wMonth,
				time.wDay,
				time.wYear,
				time.wHour,
				time.wMinute,
				time.wSecond);

		WriteFile(m_hFile, szBuffer, iLen, &dwWritten, NULL);
		}

	//	Write out the line

	WriteFile(m_hFile, sLine.GetASCIIZPointer(), sLine.GetLength(), &dwWritten, NULL);
	WriteFile(m_hFile, "\r\n", 2, &dwWritten, NULL);

	//	Flush now because we don't want to lose any info if we crash

	FlushFileBuffers(m_hFile);
	}
Example #13
0
int CG16bitFont::MeasureText (const CString &sText, int *retcyHeight) const

//	MeasureText
//
//	Returns the width of the text in pixels and optionally the height

	{
	int cxWidth = 0;
	char *pPos = sText.GetASCIIZPointer();
	char *pEndPos = pPos + sText.GetLength();

	while (pPos != pEndPos)
		{
		int iIndex = (int)(BYTE)(*pPos) - g_iStartChar;
		iIndex = max(0, iIndex);

		CharMetrics *pMetrics = (CharMetrics *)m_Metrics.GetStruct(iIndex);

		pPos++;

		//	The last character needs to have the whole width; all
		//	others just use the advance distance.
		//	(Except for spaces, which should always use the advance width
		//	otherwise, the cxWidth seems to be 0)

		if (pPos == pEndPos && iIndex != 0)
			cxWidth += pMetrics->cxWidth;
		else
			cxWidth += pMetrics->cxAdvance;
		}

	//	Done

	if (retcyHeight)
		*retcyHeight = m_cyHeight;

	return cxWidth;
	}
Example #14
0
ALERROR CTopologyNode::ParseStargateString (const CString &sStargate, CString *retsNodeID, CString *retsGateName)

//	ParseStargateString
//
//	Parses stargate from a single string ("nodeID:gateName")
//
//	Note: Callers rely on the fact that a NULL_STR input results in NULL_STR outputs (and NOERROR)

	{
	char *pPos = sStargate.GetASCIIZPointer();
	char *pStart = pPos;
	while (*pPos != ':' && *pPos != '\0')
		pPos++;

	*retsNodeID = CString(pStart, pPos - pStart);

	if (*pPos == ':')
		*retsGateName = CString(pPos + 1);
	else
		*retsGateName = NULL_STR;

	return NOERROR;
	}
Example #15
0
void GenerateShipTable (CUniverse &Universe, CXMLElement *pCmdLine, CIDTable &EntityTable)
	{
	int i, j;

	//	Some options

	bool bAllClasses = (pCmdLine->GetAttributeBool(CONSTLIT("allClasses")) || pCmdLine->GetAttributeBool(CONSTLIT("all")));

	//	Get the criteria from the command line. Always append 's' because we
	//	want ship classes.

	CString sCriteria = strPatternSubst(CONSTLIT("%s s"), pCmdLine->GetAttribute(CONSTLIT("criteria")));
	CDesignTypeCriteria Criteria;
	if (CDesignTypeCriteria::ParseCriteria(sCriteria, &Criteria) != NOERROR)
		{
		printf("ERROR: Unable to parse criteria.\n");
		return;
		}

	//	Generate a list of columns to display

	TArray<CString> Cols;
	Cols.Insert(FIELD_LEVEL);
	Cols.Insert(FIELD_NAME);

	for (i = 0; i < pCmdLine->GetAttributeCount(); i++)
		{
		CString sAttrib = pCmdLine->GetAttributeName(i);

		if (strEquals(sAttrib, FIELD_BALANCE))
			{
			Cols.Insert(CONSTLIT("balanceType"));
			Cols.Insert(CONSTLIT("combatStrength"));
			Cols.Insert(CONSTLIT("damage"));
			Cols.Insert(CONSTLIT("defenseStrength"));
			}
		else if (!IsMainCommandParam(sAttrib)
				&& !strEquals(sAttrib, CONSTLIT("shiptable")))
			{
			CString sValue = pCmdLine->GetAttribute(i);
			
			if (!strEquals(sValue, CONSTLIT("true")))
				Cols.Insert(strPatternSubst(CONSTLIT("%s:%s"), sAttrib, sValue));
			else
				Cols.Insert(sAttrib);
			}
		}

	//	Output the header

	for (j = 0; j < Cols.GetCount(); j++)
		{
		if (j != 0)
			printf("\t");

		printf(Cols[j].GetASCIIZPointer());
		}

	printf("\n");

	//	Generate a table

	CSymbolTable Table(FALSE, TRUE);

	//	Loop over all items that match and add them to
	//	a sorted table.

	for (i = 0; i < Universe.GetShipClassCount(); i++)
		{
		CShipClass *pClass = Universe.GetShipClass(i);

		//	Only include generic classes unless otherwise specified

		if (!bAllClasses && !pClass->HasLiteralAttribute(CONSTLIT("genericClass")))
			continue;

		if (!pClass->MatchesCriteria(Criteria))
			continue;

		//	Figure out the sort order

		char szBuffer[1024];
		wsprintf(szBuffer, "%04d%s%d", 
				pClass->GetLevel(),
				pClass->GetNounPhrase(0).GetASCIIZPointer(),
				pClass->GetUNID());
		Table.AddEntry(CString(szBuffer), (CObject *)pClass);
		}

	//	Output table

	for (i = 0; i < Table.GetCount(); i++)
		{
		CShipClass *pClass = (CShipClass *)Table.GetValue(i);

		//	Output each row

		for (j = 0; j < Cols.GetCount(); j++)
			{
			if (j != 0)
				printf("\t");

			const CString &sField = Cols[j];
			CString sValue;

			if (strEquals(sField, FIELD_ENTITY))
				{
				CString *pValue;
				if (EntityTable.Lookup(pClass->GetUNID(), (CObject **)&pValue) == NOERROR)
					sValue = *pValue;
				else
					sValue = CONSTLIT("?");
				}
			else
				sValue = pClass->GetDataField(sField);

			if (strEquals(sField, FIELD_MANEUVER) 
					|| strEquals(sField, FIELD_THRUST_TO_WEIGHT))
				printf("%.1f", strToInt(sValue, 0, NULL) / 1000.0);
			else if (strEquals(sField, FIELD_SCORE_CALC))
				printf("%d", pClass->CalcScore());
			else
				printf(sValue.GetASCIIZPointer());
			}

		printf("\n");
		}

	printf("\n");
	}
Example #16
0
void GenerateWordList (const CString &sDataFile, CXMLElement *pCmdLine)

//	GenerateWordList
//
//	Generate a list of unique words used in the game

{
    ALERROR error;
    int i;
    CString sError;

    //	Open the XML file

    CResourceDb Resources(sDataFile);
    if (error = Resources.Open())
    {
        printf("Unable to initialize data file.\n");
        return;
    }

    CXMLElement *pGameFile;
    if (error = Resources.LoadGameFile(&pGameFile, NULL, &sError))
    {
        printf("%s\n", sError.GetASCIIZPointer());
        return;
    }

    //	Create the context

    CSymbolTable WordList(FALSE, TRUE);
    TraverseCtx Ctx;
    Ctx.pWordList = &WordList;

    //	Recursive descent

    ParseWordList(Ctx, pGameFile);

    //	Parse all modules too

    CXMLElement *pModules = pGameFile->GetContentElementByTag(MODULES_TAG);
    if (pModules)
    {
        for (i = 0; i < pModules->GetContentElementCount(); i++)
        {
            CXMLElement *pModule = pModules->GetContentElement(i);
            CXMLElement *pModuleXML;
            if (error = Resources.LoadModule(NULL_STR, pModule->GetAttribute(FILENAME_ATTRIB), &pModuleXML, &sError))
            {
                printf("%s\n", sError.GetASCIIZPointer());
                return;
            }

            ParseWordList(Ctx, pModuleXML);
        }
    }

    //	Print out the word list

    for (i = 0; i < WordList.GetCount(); i++)
        printf("%s\n", WordList.GetKey(i).GetASCIIZPointer());
}
Example #17
0
void WordGenerator (CXMLElement *pCmdLine)
{
    int i;

    //	Load input file

    CString sFilespec = pCmdLine->GetAttribute(CONSTLIT("input"));
    if (sFilespec.IsBlank())
    {
        printf("ERROR: input filename expected.\n");
        return;
    }

    CFileReadBlock InputFile(sFilespec);
    if (InputFile.Open() != NOERROR)
    {
        printf("ERROR: Unable to open file: %s\n", sFilespec.GetASCIIZPointer());
        return;
    }

    //	"Novel" means that we only generate words that are not
    //	in the input file.

    bool bNovelWordsOnly = pCmdLine->GetAttributeBool(NOVEL_ATTRIB);

    //	Build up a word generator

    CMarkovWordGenerator Generator;
    TMap<CString, DWORD> InputWords;

    //	Read each line of the file

    char *pPos = InputFile.GetPointer(0);
    char *pEndPos = pPos + InputFile.GetLength();
    while (pPos < pEndPos)
    {
        //	Skip whitespace

        while (pPos < pEndPos && (strIsWhitespace(pPos) || *pPos < ' '))
            pPos++;

        //	Parse the line

        char *pStart = pPos;
        while (pPos < pEndPos && *pPos != '\r' && *pPos != '\n' && *pPos >= ' ')
            pPos++;

        CString sWord(pStart, pPos - pStart);

        //	Add the word to the generator

        if (!sWord.IsBlank())
        {
            Generator.AddSample(strTrimWhitespace(sWord));

            //	If we are looking for novel words we need to keep a map
            //	of all words in the input file.

            if (bNovelWordsOnly)
                InputWords.Insert(sWord);
        }
    }

    //	If we have a count, then output a list of random words

    int iCount;
    if (pCmdLine->FindAttributeInteger(COUNT_ATTRIB, &iCount))
    {
        if (iCount > 0)
        {
            TArray<CString> Result;
            Generator.GenerateUnique(iCount, &Result);

            for (i = 0; i < Result.GetCount(); i++)
                if (InputWords.Find(Result[i]))
                {
                    Result.Delete(i);
                    i--;
                }

            Result.Sort();

            for (i = 0; i < Result.GetCount(); i++)
                printf("%s\n", Result[i].GetASCIIZPointer());
        }
    }

    //	Otherwise, output the generator as XML

    else
    {
        CMemoryWriteStream Output;
        if (Output.Create() != NOERROR)
        {
            printf("ERROR: Out of memory.\n");
            return;
        }

        if (Generator.WriteAsXML(&Output) != NOERROR)
        {
            printf("ERROR: Unable to output generator as XML.\n");
            return;
        }

        Output.Write("\0", 1);
        printf(Output.GetPointer());
    }
}
Example #18
0
void GenerateEncounterTable (CUniverse &Universe, CXMLElement *pCmdLine, CIDTable &EntityTable)
	{
	ALERROR error;
	int i, j;

	//	Get the criteria from the command line. Always append 't' because we
	//	want station types.

	CString sCriteria = strPatternSubst(CONSTLIT("%s t"), pCmdLine->GetAttribute(CRITERIA_ATTRIB));

	//	Parse it

	CDesignTypeCriteria Criteria;
	if (CDesignTypeCriteria::ParseCriteria(sCriteria, &Criteria) != NOERROR)
		{
		printf("ERROR: Unable to parse criteria.\n");
		return;
		}

	bool bAll = pCmdLine->GetAttributeBool(ALL_ATTRIB);
	bool bOnlyNotRandom = pCmdLine->GetAttributeBool(ONLY_NOT_RANDOM_ATTRIB);

	//	Generate a table of all matching encounters

	CSymbolTable Table(FALSE, TRUE);

	//	Loop over all items for this level and add them to
	//	a sorted table.

	for (i = 0; i < Universe.GetStationTypeCount(); i++)
		{
		CStationType *pType = Universe.GetStationType(i);
		int iLevel = pType->GetLevel();

		//	If we're selecting all types, then do it

		if (bAll)
			;

		//	If we only want non-random types, then skip any random encounters.

		else if (bOnlyNotRandom)
			{
			if (pType->CanBeEncounteredRandomly())
				continue;
			}

		//	Otherwise we skip anything except random encounters.

		else
			{
			if (!pType->CanBeEncounteredRandomly())
				continue;
			}

		//	If we don't match the criteria, then continue

		if (!pType->MatchesCriteria(Criteria))
			continue;

		//	Get the category and name

		CString sCategory = pType->GetDataField(FIELD_CATEGORY);
		CString sName = pType->GetDataField(FIELD_NAME);
		if (*sName.GetASCIIZPointer() == '(')
			sName = strSubString(sName, 1, -1);

		//	Figure out the sort order

		char szBuffer[1024];
		wsprintf(szBuffer, "%02d%s%s%08x", 
				iLevel,
				sCategory.GetASCIIZPointer(), 
				sName.GetASCIIZPointer(),
				pType->GetUNID());
		Table.AddEntry(CString(szBuffer), (CObject *)pType);
		}

	//	Generate a list of columns to display

	TArray<CString> Cols;
	Cols.Insert(FIELD_LEVEL);
	Cols.Insert(FIELD_CATEGORY);
	Cols.Insert(FIELD_NAME);

	for (i = 0; i < pCmdLine->GetAttributeCount(); i++)
		{
		CString sAttrib = pCmdLine->GetAttributeName(i);

		if (!IsMainCommandParam(sAttrib)
				&& !strEquals(sAttrib, ONLY_NOT_RANDOM_ATTRIB)
				&& !strEquals(sAttrib, CONSTLIT("encountertable")))
			{
			CString sValue = pCmdLine->GetAttribute(i);
			
			if (!strEquals(sValue, CONSTLIT("true")))
				Cols.Insert(strPatternSubst(CONSTLIT("%s:%s"), sAttrib, sValue));
			else
				Cols.Insert(sAttrib);
			}
		}

	//	If we need to output total count, then load the table

	CDesignTypeStats TotalCount;
	if (pCmdLine->GetAttributeBool(FIELD_TOTAL_COUNT)
			|| pCmdLine->GetAttributeBool(FIELD_COUNT_DISTRIBUTION))
		{
		if (error = LoadDesignTypeStats(&TotalCount))
			return;
		}

	//	If we've got any entries in the table, output now

	if (Table.GetCount())
		{
		//	Output the header

		for (j = 0; j < Cols.GetCount(); j++)
			{
			if (j != 0)
				printf("\t");

			printf(Cols[j].GetASCIIZPointer());
			}

		printf("\n");

		//	Output each row

		for (i = 0; i < Table.GetCount(); i++)
			{
			CStationType *pType = (CStationType *)Table.GetValue(i);

			for (j = 0; j < Cols.GetCount(); j++)
				{
				if (j != 0)
					printf("\t");

				const CString &sField = Cols[j];

				//	Get the value

				CString sValue;
				if (strEquals(sField, FIELD_ENTITY))
					{
					CString *pValue;
					if (EntityTable.Lookup(pType->GetUNID(), (CObject **)&pValue) == NOERROR)
						sValue = *pValue;
					else
						sValue = CONSTLIT("?");
					}
				else
					sValue = pType->GetDataField(sField);

				//	Format and output

				if (strEquals(sField, FIELD_FIRE_RATE_ADJ))
					printf("%.2f", strToInt(sValue, 0, NULL) / 1000.0);
				else if (strEquals(sField, FIELD_TOTAL_COUNT))
					{
					SDesignTypeInfo *pInfo = TotalCount.GetAt(pType->GetUNID());
					double rCount = (pInfo ? pInfo->rPerGameMeanCount : 0.0);
					printf("%.2f", rCount);
					}
				else if (strEquals(sField, FIELD_COUNT_DISTRIBUTION))
					{
					SDesignTypeInfo *pInfo = TotalCount.GetAt(pType->GetUNID());
					printf("%s", (pInfo ? pInfo->sDistribution : NULL_STR).GetASCIIZPointer());
					}
				else
					printf(sValue.GetASCIIZPointer());
				}

			printf("\n");
			}

		printf("\n");
		}
	else
		printf("No entries match criteria.\n");
	}
Example #19
0
bool CG16bitFont::ParseFontDesc (const CString &sDesc, CString *retsTypeface, int *retiSize, bool *retbBold, bool *retbItalic)

//	ParseFontDesc
//
//	Parses a string of the form:
//
//	{typeface} {font-size} [bold] [italic]
//
//	Returns TRUE if valid

	{
	char *pPos = sDesc.GetASCIIZPointer();
	CString sTypeface = CONSTLIT("Arial");
	int iSize = 16;
	bool bBold = false;
	bool bItalic = false;

	//	Skip whitespace

	while (*pPos == ' ' || *pPos == '\t')
		pPos++;

	//	Skip delimiters

	bool bSpaceDelimiter;
	if (*pPos == '\'' || *pPos == '\"')
		{
		bSpaceDelimiter = false;
		pPos++;
		}
	else
		bSpaceDelimiter = true;

	//	Look for typeface

	char *pStart = pPos;
	while (*pPos != '\'' && *pPos != '\"' && (!bSpaceDelimiter || *pPos != ' ') && *pPos != '\0')
		pPos++;

	sTypeface = CString(pStart, pPos - pStart);

	//	Look for size

	while ((*pPos < '0' || *pPos > '9') && *pPos != '\0')
		pPos++;

	if (*pPos == '\0')
		{
		//printf("DirectXFont: Expected font size.");
		return false;
		}

	iSize = strParseInt(pPos, -1, &pPos);
	if (iSize == -1)
		{
		//printf("DirectXFont: Invalid font size.");
		return false;
		}

	//	Skip whitespace

	while (*pPos == ' ' || *pPos == '\t')
		pPos++;

	//	Parse bold/italic

	pStart = pPos;
	bool bDone = (*pPos == '\0');
	while (!bDone)
		{
		if (*pPos == ' ' || *pPos == '\0')
			{
			CString sStyle = CString(pStart, pPos - pStart);
			if (strEquals(sStyle, CONSTLIT("bold")))
				bBold = true;
			else if (strEquals(sStyle, CONSTLIT("italic")))
				bItalic = true;

			//	Skip whitespace

			while (*pPos == ' ')
				pPos++;

			pStart = pPos;
			bDone = (*pPos == '\0');
			}
		else
			pPos++;
		}

	//	Done

	*retsTypeface = sTypeface;
	*retiSize = iSize;
	*retbBold = bBold;
	*retbItalic = bItalic;

	return true;
	}
Example #20
0
CString CNPServer::CmdLogin (ClientCtx *pClient, const CDataPackStruct &Data)
	{
	//	If we're already logged in, then fail (for now)

	if (pClient->ACL != aclNoLogin)
		return ComposeCmdFail(pClient, CMD_LOGIN, LITERAL("You are already logged in."));

	//	Get the data

	CString sName = Data.GetStringItem(1);
	CString sPassword = Data.GetStringItem(2);

	Lock();

	//	Check for overlord

	if (strCompare(sName, LITERAL("overlord")) == 0)
		{
		//	Check the password

		if (strCompare(sPassword, m_sOverlordPassword) != 0)
			{
			Unlock();
			return ComposeCmdFail(pClient, CMD_LOGIN, LITERAL("Invalid name or password."));
			}

		//	Complete login

		pClient->sName = LITERAL("Overlord");
		pClient->ACL = aclOverlord;
		pClient->pSovereign = m_pUniv->GetSovereign(m_pUniv->GetOverlordUNID());

		Log("[%d] Login as Overlord", pClient->dwClientID);
		}

	//	Check for guest

	else if (strCompare(sName, LITERAL("guest")) == 0)
		{
		//	Not allowed, for now

		Unlock();
		return ComposeCmdFail(pClient, CMD_LOGIN, LITERAL("Guest access not allowed in this universe."));
		}

	//	A player

	else
		{
		//	Look-up the player

		CNPHumanPlayer *pPlayer;
		if (m_Players.Lookup(sName, (CObject **)&pPlayer) != NOERROR)
			{
			Unlock();
			return ComposeCmdFail(pClient, CMD_LOGIN, LITERAL("Invalid name or password."));
			}

		//	Check the password

		if (strCompare(sPassword, pPlayer->GetPassword()) != 0)
			{
			Unlock();
			return ComposeCmdFail(pClient, CMD_LOGIN, LITERAL("Invalid name or password."));
			}

		//	Complete login

		pClient->sName = sName;
		pClient->ACL = aclPlayer;
		pClient->pSovereign = m_pUniv->GetSovereign(pPlayer->GetSovereignID());

		Log("[%d] Login as %s", pClient->dwClientID, sName.GetASCIIZPointer());
		}

	//	Compose reply

	CDataPackStruct Reply;
	Reply.AppendInteger(RES_LOGIN);
	Reply.AppendInteger(pClient->pSovereign->GetUNID());
	Reply.AppendInteger(m_pUniv->GetTurn());
	Reply.AppendString(pClient->pSovereign->GetName());

	Unlock();

	return Reply.SerializeToString();
	}
Example #21
0
int CG16bitFont::BreakText (const CString &sText, int cxWidth, TArray<CString> *retLines, DWORD dwFlags) const

//	BreakText
//
//	Splits the given string into multiple lines so that they fit
//	in the given width

	{
	char *pPos = sText.GetASCIIZPointer();
	char *pStartLine = pPos;
	int iCharsInLine = 0;
	char *pStartWord = pPos;
	int iCharsInWord = 0;
	int cxWordWidth = 0;
	int cxRemainingWidth = cxWidth;
	int iLines = 0;

	//	Can't handle 0 widths

	if (cxWidth == 0)
		return 0;

	//	Smart quotes

	bool bInSmartQuotes = false;
	bool *ioInSmartQuotes;
	if (dwFlags & SmartQuotes)
		ioInSmartQuotes = &bInSmartQuotes;
	else
		ioInSmartQuotes = NULL;

	//	If we need to truncate, then we need to adjust the width

	if (dwFlags & TruncateLine)
		{
		cxWidth -= MeasureText(STR_ELLIPSIS);
		if (cxWidth < 0)
			return 0;
		}

	//	Do it

	bool bTruncate = false;
	while (*pPos != '\0')
		{
		//	If we've got a carriage return then we immediately end
		//	the line.

		if (*pPos == '\n')
			{
			//	Add the current word to the line

			iCharsInLine += iCharsInWord;

			//	Add the line to the array

			FormatLine(pStartLine, iCharsInLine, ioInSmartQuotes, retLines);
			iLines++;

			//	Reset the line and word

			pStartLine = pPos + 1;
			pStartWord = pStartLine;
			iCharsInLine = 0;
			iCharsInWord = 0;
			cxWordWidth = 0;
			cxRemainingWidth = cxWidth;

			//	Reset smartquotes (sometimes we end a paragraph without closing
			//	a quote. In that case, we need to start with an open quote).

			bInSmartQuotes = false;

			//	If we're truncating, we're out of here (we don't add an ellipsis)

			if (dwFlags & TruncateLine)
				break;
			}

		//	Otherwise, continue by trying to add the character to the word

		else
			{
			char chChar = *pPos;
			if (chChar == '"' && ioInSmartQuotes) chChar = '“';

			//	Get the metrics for the character

			int iIndex = (int)(BYTE)chChar - g_iStartChar;
			iIndex = max(0, iIndex);

			CharMetrics *pMetrics = (CharMetrics *)m_Metrics.GetStruct(iIndex);

			//	Does the character fit in the line?

			bool bCharFits = ((cxRemainingWidth - cxWordWidth) >= pMetrics->cxWidth);

			//	If the character doesn't fit, then we've reached the end
			//	of the line.

			if (!bCharFits)
				{
				//	If the character is a space then the entire word should
				//	fit on the line

				if (*pPos == ' ')
					{
					iCharsInLine += iCharsInWord;

					//	Reset the word

					pStartWord = pPos + 1;
					iCharsInWord = 0;
					cxWordWidth = 0;
					}

				//	If this is the first word in the line then we need to break
				//	up the word across lines.

				if (iCharsInLine == 0)
					{
					//	Add what we've got to the array

					FormatLine(pStartWord, iCharsInWord, ioInSmartQuotes, retLines);
					iLines++;

					//	Reset the word

					pStartWord = pPos;
					iCharsInWord = 1;
					cxWordWidth = pMetrics->cxAdvance;
					}

				//	Otherwise, add the line to the array

				else
					{
					FormatLine(pStartLine, iCharsInLine, ioInSmartQuotes, retLines);
					iLines++;

					//	Reset the line

					pStartLine = pStartWord;
					iCharsInLine = 0;
					cxRemainingWidth = cxWidth;

					//	Add the character that didn't fit to the word

					if (*pPos != ' ')
						{
						iCharsInWord++;
						cxWordWidth += pMetrics->cxAdvance;
						}
					}

				//	Done if we're truncating

				if (dwFlags & TruncateLine)
					{
					iCharsInLine = 0;
					iCharsInWord = 0;
					bTruncate = true;
					break;
					}
				}

			//	Otherwise, if it does fit, add it to the end of the word

			else
				{
				iCharsInWord++;
				cxWordWidth += pMetrics->cxAdvance;

				//	If this character is a space or a hyphen, add it to the
				//	end of the line

				if (*pPos == ' ' || *pPos == '-')
					{
					iCharsInLine += iCharsInWord;
					cxRemainingWidth -= cxWordWidth;

					//	Reset the word

					pStartWord = pPos + 1;
					iCharsInWord = 0;
					cxWordWidth = 0;
					}
				}
			}

		//	Next character
		
		pPos++;
		}

	//	Add the remainder

	iCharsInLine += iCharsInWord;
	if (iCharsInLine)
		{
		FormatLine(pStartLine, iCharsInLine, ioInSmartQuotes, retLines);
		iLines++;
		}

	//	Add ellipsis, if necessary

	if (bTruncate && retLines)
		retLines->GetAt(0).Append(STR_ELLIPSIS);

	//	Return the lines

	return iLines;
	}
Example #22
0
void GenerateTypeTable (CUniverse &Universe, CXMLElement *pCmdLine)
	{
	int i, j;

	//	Get the criteria from the command line.

	CString sCriteria = pCmdLine->GetAttribute(CRITERIA_ATTRIB);

	//	Parse it

	CDesignTypeCriteria Criteria;
	if (CDesignTypeCriteria::ParseCriteria(sCriteria, &Criteria) != NOERROR)
		{
		printf("ERROR: Unable to parse criteria.\n");
		return;
		}

	//	Generate a table of all matching types

	TSortMap<CString, CDesignType *> Table;

	//	Loop over all items for this level and add them to
	//	a sorted table.

	for (i = 0; i < Universe.GetDesignTypeCount(); i++)
		{
		CDesignType *pType = Universe.GetDesignType(i);
		int iLevel = pType->GetLevel();

		if (!pType->MatchesCriteria(Criteria))
			continue;

		//	Get the name

		CString sName = pType->GetDataField(FIELD_NAME);
		if (*sName.GetASCIIZPointer() == '(')
			sName = strSubString(sName, 1, -1);

		//	Figure out the sort order

		char szBuffer[1024];
		wsprintf(szBuffer, "%02d%s%08x", 
				iLevel,
				sName.GetASCIIZPointer(),
				pType->GetUNID());
		Table.Insert(CString(szBuffer), pType);
		}

	//	Generate a list of columns to display

	TArray<CString> Cols;
	Cols.Insert(FIELD_LEVEL);
	Cols.Insert(FIELD_NAME);

	for (i = 0; i < pCmdLine->GetAttributeCount(); i++)
		{
		CString sAttrib = pCmdLine->GetAttributeName(i);

		if (!IsMainCommandParam(sAttrib)
				&& !strEquals(sAttrib, CONSTLIT("typetable")))
			{
			CString sValue = pCmdLine->GetAttribute(i);
			
			if (!strEquals(sValue, CONSTLIT("true")))
				Cols.Insert(strPatternSubst(CONSTLIT("%s:%s"), sAttrib, sValue));
			else
				Cols.Insert(sAttrib);
			}
		}

	//	If we need to output total count, then load the table

	CDesignTypeStats TotalCount;
	if (pCmdLine->GetAttributeBool(FIELD_TOTAL_COUNT)
			|| pCmdLine->GetAttributeBool(FIELD_COUNT_DISTRIBUTION))
		{
		if (LoadDesignTypeStats(Universe.GetDesignCollection().GetAdventureUNID(), &TotalCount) != NOERROR)
			{
			printf("ERROR: Unable to load type count table.\n");
			return;
			}
		}

	//	If we've got any entries in the table, output now

	if (Table.GetCount())
		{
		//	Output the header

		for (j = 0; j < Cols.GetCount(); j++)
			{
			if (j != 0)
				printf("\t");

			printf(Cols[j].GetASCIIZPointer());
			}

		printf("\n");

		//	Output each row

		CCodeChainCtx CCCtx;
		for (i = 0; i < Table.GetCount(); i++)
			{
			CDesignType *pType = Table[i];

			for (j = 0; j < Cols.GetCount(); j++)
				{
				if (j != 0)
					printf("\t");

				const CString &sField = Cols[j];

				//	Format and output

				if (strEquals(sField, FIELD_TOTAL_COUNT))
					{
					SDesignTypeInfo *pInfo = TotalCount.GetAt(pType->GetUNID());
					double rCount = (pInfo ? pInfo->rPerGameMeanCount : 0.0);
					printf("%.2f", rCount);
					}
				else if (strEquals(sField, FIELD_COUNT_DISTRIBUTION))
					{
					SDesignTypeInfo *pInfo = TotalCount.GetAt(pType->GetUNID());
					printf("%s", (pInfo ? pInfo->sDistribution : NULL_STR).GetASCIIZPointer());
					}
				else
					{
					ICCItem *pResult = pType->GetProperty(CCCtx, sField);
					CString sValue = pResult->Print(&g_pUniverse->GetCC(), PRFLAG_NO_QUOTES | PRFLAG_ENCODE_FOR_DISPLAY);
					pResult->Discard(&g_pUniverse->GetCC());

					printf(sValue.GetASCIIZPointer());
					}
				}

			printf("\n");
			}

		printf("\n");
		}
	else
		printf("No entries match criteria.\n");
	}
Example #23
0
ALERROR CItemEnhancement::InitFromDesc (const CString &sDesc, CString *retsError)

//	InitFromDesc
//
//	Initializes from a string of the following forms:
//
//	{number}					Interpret as a mod code
//	+armor:{n}					Add	armor special damage, where n is an item level
//	+hpBonus:{n}				Add hp bonus.
//	+immunity:{s}				Immunity to special damage s.
//	+reflect:{s}				Reflects damage type s.
//	+regen						Regenerate
//	+resist:{s}:{n}				DamageAdj for type s set to n
//	+resistDamageClass:{s}:{n}	DamageAdj for type s (and its next-tier mate) set to n
//	+resistDamageTier:{s}:{n}	DamageAdj for type s (and its tier mate) set to n
//	+resistEnergy:{n}			DamageAdj for energy damage set to n
//	+resistMatter:{n}			DamageAdj for matter damage set to n
//	+shield:{n}					Add shield disrupt special damage, where n is an item level
//	+speed:{n}					Faster. n is new delay value as a percent of normal

{
    //	If the string is a number then we interpret it as a mod code.

    bool bFailed;
    DWORD dwCode = strToInt(sDesc, 0, &bFailed);
    if (!bFailed)
    {
        m_dwMods = dwCode;
        return NOERROR;
    }

    //	Parse the string

    char *pPos = sDesc.GetASCIIZPointer();

    //	Expect either "+" or "-" (for disadvantage)

    bool bDisadvantage;
    if (*pPos == '+')
        bDisadvantage = false;
    else if (*pPos == '-')
        bDisadvantage = true;
    else
    {
        if (retsError)
            *retsError = CONSTLIT("Invalid enhancement description: expected '+' or '-'.");
        return ERR_FAIL;
    }

    pPos++;

    //	Parse the enhancement name

    char *pStart = pPos;
    while (*pPos != ':' && *pPos != '\0')
        pPos++;

    CString sID(pStart, (int)(pPos - pStart));

    //	See if we have a value

    int iValue = 0;
    CString sValue;
    if (*pPos == ':')
    {
        pPos++;

        if (*pPos == '-' || *pPos == '+' || (*pPos >= '0' && *pPos <= '9'))
            iValue = strParseInt(pPos, 0, &pPos);
        else
        {
            char *pStart = pPos;
            while (*pPos != '\0' && *pPos != ':')
                pPos++;

            sValue = CString(pStart, (int)(pPos - pStart));
        }
    }

    //	See if we have a second value

    int iValue2 = 0;
    if (*pPos == ':')
    {
        pPos++;
        iValue2 = strParseInt(pPos, 0, &pPos);
    }

    //	See if this is an hpBonus

    if (strEquals(sID, CONSTLIT("hpBonus")))
    {
        if (bDisadvantage && iValue > 0)
            iValue = -iValue;

        if (iValue < -100)
        {
            if (retsError)
                *retsError = CONSTLIT("hpBonus penalty cannot exceed 100%.");
            return ERR_FAIL;
        }
        else if (iValue < 0)
            SetModCode(EncodeAX(etHPBonus | etDisadvantage, 0, -iValue));
        else if (iValue == 0)
            SetModCode(Encode12(etStrengthen));
        else if (iValue <= 1000)
            SetModCode(EncodeAX(etHPBonus, 0, iValue));
        else
        {
            if (retsError)
                *retsError = CONSTLIT("hpBonus cannot exceed 1000%.");
            return ERR_FAIL;
        }
    }

    //	Immunity

    else if (strEquals(sID, CONSTLIT("immunity")))
    {
        if (strEquals(sValue, CONSTLIT("ionEffects")))
            m_dwMods = Encode12(etImmunityIonEffects);
        else
        {
            SpecialDamageTypes iSpecial = DamageDesc::ConvertToSpecialDamageTypes(sValue);
            switch (iSpecial)
            {
            case specialRadiation:
            case specialBlinding:
            case specialEMP:
            case specialDeviceDamage:
            case specialDisintegration:
            case specialMomentum:
            case specialShieldDisrupt:
            case specialDeviceDisrupt:
            case specialShatter:
            {
                if (bDisadvantage)
                {
                    if (retsError)
                        *retsError = CONSTLIT("Disadvantage not supported.");
                    return ERR_FAIL;
                }

                SetModImmunity(iSpecial);
                break;
            }

            default:
            {
                if (retsError)
                    *retsError = strPatternSubst(CONSTLIT("Invalid immunity: %s"), sID);
                return ERR_FAIL;
            }
            }
        }
    }

    //	Reflect bonus

    else if (strEquals(sID, CONSTLIT("reflect")))
    {
        DamageTypes iDamageType = LoadDamageTypeFromXML(sValue);
        if (iDamageType == damageError)
        {
            if (retsError)
                *retsError = strPatternSubst(CONSTLIT("Invalid damage type: %s"), sValue);
            return ERR_FAIL;
        }

        SetModReflect(iDamageType);
    }

    //	Regen

    else if (strEquals(sID, CONSTLIT("regen")))
    {
        m_dwMods = Encode12(etRegenerate | (bDisadvantage ? etDisadvantage : 0));
    }

    //	Resist damage

    else if (strEquals(sID, CONSTLIT("resist")))
    {
        DamageTypes iDamageType = LoadDamageTypeFromXML(sValue);
        if (iDamageType == damageError)
        {
            if (retsError)
                *retsError = strPatternSubst(CONSTLIT("Invalid damage type: %s"), sValue);
            return ERR_FAIL;
        }

        SetModResistDamage(iDamageType, iValue2);
    }

    //	Resist damage

    else if (strEquals(sID, CONSTLIT("resistDamageClass")))
    {
        DamageTypes iDamageType = LoadDamageTypeFromXML(sValue);
        if (iDamageType == damageError)
        {
            if (retsError)
                *retsError = strPatternSubst(CONSTLIT("Invalid damage type: %s"), sValue);
            return ERR_FAIL;
        }

        SetModResistDamageClass(iDamageType, iValue2);
    }

    //	Resist damage tier

    else if (strEquals(sID, CONSTLIT("resistDamageTier")))
    {
        DamageTypes iDamageType = LoadDamageTypeFromXML(sValue);
        if (iDamageType == damageError)
        {
            if (retsError)
                *retsError = strPatternSubst(CONSTLIT("Invalid damage type: %s"), sValue);
            return ERR_FAIL;
        }

        SetModResistDamageTier(iDamageType, iValue2);
    }

    //	Resist energy/matter

    else if (strEquals(sID, CONSTLIT("resistEnergy")))
        SetModResistEnergy(iValue);
    else if (strEquals(sID, CONSTLIT("resistMatter")))
        SetModResistMatter(iValue);

    //	Speed bonus

    else if (strEquals(sID, CONSTLIT("speed")))
    {
        if (iValue <= 0)
        {
            if (retsError)
                *retsError = strPatternSubst(CONSTLIT("Invalid speed value: %s."), iValue);
            return ERR_FAIL;
        }
        else
            //	LATER: Support min and max delay limits
            SetModSpeed(iValue);
    }

    //	Otherwise, see if this is a special damage

    else
    {
        SpecialDamageTypes iSpecial = DamageDesc::ConvertToSpecialDamageTypes(sID);
        switch (iSpecial)
        {
        case specialArmor:
        case specialShieldDisrupt:
        {
            if (bDisadvantage)
            {
                if (retsError)
                    *retsError = CONSTLIT("Disadvantage not supported.");
                return ERR_FAIL;
            }

            if (iValue < 1 || iValue > MAX_ITEM_LEVEL)
            {
                if (retsError)
                    *retsError = strPatternSubst(CONSTLIT("Invalid %s damage level: %d"), sID, iValue);
                return ERR_FAIL;
            }

            SetModSpecialDamage(iSpecial, iValue);
            break;
        }

        default:
        {
            if (retsError)
                *retsError = strPatternSubst(CONSTLIT("Invalid enhancement name: %s"), sID);
            return ERR_FAIL;
        }
        }
    }

    //	Done

    return NOERROR;
}
Example #24
0
IEffectPainter *CEffectCreator::CreatePainterFromStream (SLoadCtx &Ctx, bool bNullCreator)

//	CreatePainterFromStream
//
//	Load a painter from a stream

	{
	CEffectCreator *pCreator;

	//	For previous versions, we only stored UNID if we had a creator

	if (Ctx.dwVersion < 43 && bNullCreator)
		return NULL;

	//	At version 15 we started saving versions as string UNIDs. We need to do this
	//	because sometimes the effect creator is inside a weapon fire desc
	//	structure (also identified by string UNIDs).

	if (Ctx.dwVersion >= 15)
		{
		CString sUNID;
		sUNID.ReadFromStream(Ctx.pStream);

		pCreator = (sUNID.IsBlank() ? NULL : CEffectCreator::FindEffectCreator(sUNID));

		//	Load the creator class that saved the painter

		if (IEffectPainter::ValidateClass(Ctx, (pCreator ? pCreator->GetTag() : NULL_STR)) != NOERROR)
			return NULL;

		//	Error

		if (pCreator == NULL)
			{
			if (!sUNID.IsBlank())
				kernelDebugLogMessage("Invalid painter creator: %s", sUNID.GetASCIIZPointer());
			return NULL;
			}
		}

	//	Old style uses DWORD UNIDs

	else
		{
		//	The first DWORD is the UNID of the creator

		DWORD dwUNID;
		Ctx.pStream->Read((char *)&dwUNID, sizeof(DWORD));
		if (dwUNID == 0)
			return NULL;

		pCreator = g_pUniverse->FindEffectType(dwUNID);

		//	Error

		if (pCreator == NULL)
			{
			kernelDebugLogMessage("Invalid painter creator: %x", dwUNID);
			return NULL;
			}
		}

	//	Let the creator create the object

	IEffectPainter *pPainter = pCreator->CreatePainter();

	//	Load it

	pPainter->ReadFromStream(Ctx);

	//	Done

	return pPainter;
	}
Example #25
0
ICCItem *CCodeChain::Eval (CEvalContext *pEvalCtx, ICCItem *pItem)

//	Eval
//
//	Evaluates the given item and returns a result

{
    //	Errors always evaluate to themselves

    if (pItem->IsError())
        return pItem->Reference();

    //	If this item is quoted, then return an unquoted item

    if (pItem->IsQuoted())
    {
        //	If this is a literal symbol table then we need to evaluate its
        //	values.

        if (pItem->IsSymbolTable())
            return EvalLiteralStruct(pEvalCtx, pItem);

        //	HACK: We clone the item so that when we try to modify a literal list we
        //	mody a copy instead of the original.

        else
        {
            ICCItem *pResult = pItem->Clone(this);
            pResult->ClearQuoted();
            return pResult;
        }
    }

    //	Evaluate differently depending on whether or not
    //	this is an atom or a list. If it is an atom, either return
    //	the value or look up the atom in a symbol table. If the item
    //	is a list, try to evaluate as a function

    else if (pItem->IsIdentifier())
        return Lookup(pEvalCtx, pItem);

    //	If this is an expression (a list with multiple terms) then we
    //	try to evaluate it.

    else if (pItem->IsExpression())
    {
        ICCItem *pFunctionName;
        ICCItem *pFunction;
        ICCItem *pArgs;
        ICCItem *pResult;

        //	The first element of the list is the function

        pFunctionName = pItem->Head(this);

        //	We must have a first element since this is a list (but not Nil)

        ASSERT(pFunctionName);

        //	If this is an identifier, then look up the function
        //	in the global symbols

        if (pFunctionName->IsIdentifier())
            pFunction = LookupFunction(pEvalCtx, pFunctionName);

        //	Otherwise, evaluate it

        else
            pFunction = Eval(pEvalCtx, pFunctionName);

        //	If we get an error, return it

        if (pFunction->IsError())
            return pFunction;

        //	Make sure this is a function

        if (!pFunction->IsFunction())
        {
            pFunction->Discard(this);
            return CreateError(LITERAL("Function name expected"), pFunctionName);
        }

        //	Get the arguments

        pArgs = pItem->Tail(this);

        //	Do it

        pResult = pFunction->Execute(pEvalCtx, pArgs);

        //	Handle error by appending the function call that failed

        if (pResult->IsError())
        {
            CCString *pError = dynamic_cast<CCString *>(pResult);
            if (pError)
            {
                CString sError = pError->GetValue();
                if (!sError.IsBlank())
                {
                    char *pPos = sError.GetASCIIZPointer() + sError.GetLength() - 1;
                    if (*pPos != '#')
                    {
                        sError.Append(strPatternSubst(CONSTLIT(" ### %s ###"), pItem->Print(this)));
                        pError->SetValue(sError);
                    }
                }
            }
        }

        //	Done

        pFunction->Discard(this);
        pArgs->Discard(this);
        return pResult;
    }

    //	Anything else is a literal so we return it.

    else
        return pItem->Reference();

}
Example #26
0
CString CNPServer::CmdNewPlayer (ClientCtx *pClient, const CDataPackStruct &Data)
	{
	ALERROR error;

	//	Unless we're overlord or the universe has open access
	//	we cannot create a new player

	if (pClient->ACL != aclOverlord	&& !m_bOpenAccess)
		return ComposeCmdFail(pClient, CMD_NEW_PLAYER, LITERAL("You are not authorized to create new player accounts."));

	//	Create the new player

	CString sEmperorName = Data.GetStringItem(1);
	CString sPassword = Data.GetStringItem(2);
	CString sEmpireName = Data.GetStringItem(3);

	Lock();

	//	Make sure there isn't a player with that name already

	if (m_Players.Lookup(sEmperorName, NULL) == NOERROR)
		{
		Unlock();
		return ComposeCmdFail(pClient, CMD_NEW_PLAYER, LITERAL("A player with that name already exists."));
		}

	//	Pick a capital for this player

	int i;
	CNPWorld *pCapital = NULL;
	for (i = 0; i < m_pUniv->GetNullPointCount(); i++)
		{
		CNPNullPoint *pNP = m_pUniv->GetNullPointByIndex(i);

		int j;
		for (j = 0; j < pNP->GetWorldCount(); j++)
			{
			CNPWorld *pWorld = pNP->GetWorld(j);

			if (pWorld->HasTrait(traitReservedCapital)
					&& pWorld->GetSovereign()->GetUNID() == m_pUniv->GetIndependentUNID())
				{
				pCapital = pWorld;
				break;
				}
			}

		if (pCapital)
			break;
		}

	//	If we could not find a capital then we cannot create a new empire

	if (pCapital == NULL)
		{
		Unlock();
		return ComposeCmdFail(pClient, CMD_NEW_PLAYER, LITERAL("A world suitable for an empire's capital could not be found."));
		}

	//	Create the player

	CNPHumanPlayer *pPlayer;
	if (error = CNPHumanPlayer::Create(m_pUniv, sEmperorName, sPassword, sEmpireName, pCapital, &pPlayer))
		{
		Unlock();
		return ComposeCmdError(pClient, CMD_NEW_PLAYER, error);
		}

	//	Add it to our list

	if (error = m_Players.AddEntry(sEmperorName, pPlayer))
		{
#ifdef LATER
		//	delete the sovereign and the player
#endif
		Unlock();
		return ComposeCmdError(pClient, CMD_NEW_PLAYER, error);
		}

	Unlock();

	Log("[%d] New account created for %s", pClient->dwClientID, sEmperorName.GetASCIIZPointer());
	return ComposeCmdSuccess(pClient, CMD_NEW_PLAYER);
	}