예제 #1
0
void CUIHUD3D::SpawnHudEntities()
{
	RemoveHudEntities();

	if(gEnv->IsEditor() && gEnv->IsEditing())
		return;

	XmlNodeRef node = gEnv->pSystem->LoadXmlFromFile(HUD3D_PREFAB_LIB);

	if(node)
	{
		// get the prefab with the name defined in HUD3D_PREFAB_NAME
		XmlNodeRef prefab = NULL;

		for(int i = 0; i < node->getChildCount(); ++i)
		{
			const char *name = node->getChild(i)->getAttr("Name");

			if(name && strcmp(name, HUD3D_PREFAB_NAME) == 0)
			{
				prefab = node->getChild(i);
				prefab = prefab ? prefab->findChild("Objects") : XmlNodeRef();
				break;
			}
		}

		if(prefab)
		{
			// get the PIVOT entity and collect childs
			XmlNodeRef pivotNode = NULL;
			std::vector<XmlNodeRef> childs;
			const int count = prefab->getChildCount();
			childs.reserve(count-1);

			for(int i = 0; i < count; ++i)
			{
				const char *name = prefab->getChild(i)->getAttr("Name");

				if(strcmp("PIVOT", name) == 0)
				{
					assert(pivotNode == NULL);
					pivotNode = prefab->getChild(i);
				}
				else
				{
					childs.push_back(prefab->getChild(i));
				}
			}

			if(pivotNode)
			{
				// spawn pivot entity
				IEntityClass *pEntClass = gEnv->pEntitySystem->GetClassRegistry()->FindClass(pivotNode->getAttr("EntityClass"));

				if(pEntClass)
				{
					SEntitySpawnParams params;
					params.nFlags = ENTITY_FLAG_CLIENT_ONLY;
					params.pClass = pEntClass;
					m_pHUDRootEntity = gEnv->pEntitySystem->SpawnEntity(params);
				}

				if(!m_pHUDRootEntity) return;

				m_HUDRootEntityId = m_pHUDRootEntity->GetId();

				// spawn the childs and link to the pivot enity
				for(std::vector<XmlNodeRef>::iterator it = childs.begin(); it != childs.end(); ++it)
				{
					XmlNodeRef child = *it;
					pEntClass = gEnv->pEntitySystem->GetClassRegistry()->FindClass(child->getAttr("EntityClass"));

					if(pEntClass)
					{
						const char *material = child->getAttr("Material");
						Vec3 pos;
						Vec3 scale;
						Quat rot;
						child->getAttr("Pos", pos);
						child->getAttr("Rotate", rot);
						child->getAttr("Scale", scale);

						SEntitySpawnParams params;
						params.nFlags = ENTITY_FLAG_CLIENT_ONLY;
						params.pClass = pEntClass;
						params.vPosition = pos;
						params.qRotation = rot;
						params.vScale = scale;
						IEntity *pEntity = gEnv->pEntitySystem->SpawnEntity(params);

						if(pEntity)
						{
							IScriptTable *pScriptTable = pEntity->GetScriptTable();

							if(pScriptTable)
							{
								SmartScriptTable probs;
								pScriptTable->GetValue("Properties", probs);

								XmlNodeRef properties = child->findChild("Properties");

								if(probs && properties)
								{
									for(int k = 0; k < properties->getNumAttributes(); ++k)
									{
										const char *sKey;
										const char *sVal;
										properties->getAttributeByIndex(k, &sKey, &sVal);
										probs->SetValue(sKey, sVal);
									}
								}

								Script::CallMethod(pScriptTable,"OnPropertyChange");
							}

							if(material)
							{
								IMaterial *pMat = gEnv->p3DEngine->GetMaterialManager()->LoadMaterial(material);

								if(pMat)
									pEntity->SetMaterial(pMat);
							}

							m_pHUDRootEntity->AttachChild(pEntity);
							m_HUDEnties.push_back(pEntity->GetId());
						}
					}
				}
			}
		}
	}

	OnVisCVarChange(NULL);
}
//------------------------------------------------------------------------
void CGameRulesManager::Init()
{
	XmlNodeRef root = gEnv->pSystem->LoadXmlFromFile( GAMERULES_DEFINITIONS_XML_PATH );

	if (root)
	{
		if (!stricmp(root->getTag(), "Modes"))
		{
			IGameRulesSystem *pGameRulesSystem = g_pGame->GetIGameFramework()->GetIGameRulesSystem();
			int numModes = root->getChildCount();

			for (int i = 0; i < numModes; ++ i)
			{
				XmlNodeRef modeXml = root->getChild(i);

				if (!stricmp(modeXml->getTag(), "GameMode"))
				{
					const char *modeName;

					if (modeXml->getAttr("name", &modeName))
					{
						pGameRulesSystem->RegisterGameRules(modeName, "GameRules");
						SGameRulesData gameRulesData;
						int numModeChildren = modeXml->getChildCount();

						for (int j = 0; j < numModeChildren; ++ j)
						{
							XmlNodeRef modeChildXml = modeXml->getChild(j);
							const char *nodeTag = modeChildXml->getTag();

							if (!stricmp(nodeTag, "Alias"))
							{
								const char *alias;

								if (modeChildXml->getAttr("name", &alias))
								{
									pGameRulesSystem->AddGameRulesAlias(modeName, alias);
								}
							}
							else if (!stricmp(nodeTag, "LevelLocation"))
							{
								const char *path;

								if (modeChildXml->getAttr("path", &path))
								{
									pGameRulesSystem->AddGameRulesLevelLocation(modeName, path);
								}
							}
							else if (!stricmp(nodeTag, "Rules"))
							{
								const char *path;

								if (modeChildXml->getAttr("path", &path))
								{
									gameRulesData.m_rulesXMLPath = path;
								}
							}
							else if( !stricmp(nodeTag, "DefaultHudState"))
							{
								const char *name;

								if (modeChildXml->getAttr("name", &name))
								{
									gameRulesData.m_defaultHud = name;
								}
							}
						}

						// Check if we're a team game
						if (!gameRulesData.m_rulesXMLPath.empty())
						{
							XmlNodeRef rulesXml = gEnv->pSystem->LoadXmlFromFile( gameRulesData.m_rulesXMLPath.c_str() );

							if (rulesXml)
							{
								XmlNodeRef teamXml = rulesXml->findChild("Teams");
								gameRulesData.m_bIsTeamGame = (teamXml != (IXmlNode *)NULL);
							}
						}

						// Insert gamerule specific data
						m_rulesData.insert(TDataMap::value_type(modeName, gameRulesData));
					}
					else
					{
						CryLogAlways("CGameRulesModulesManager::Init(), invalid 'GameMode' node, requires 'name' attribute");
					}
				}
				else
				{
					CryLogAlways("CGameRulesModulesManager::Init(), invalid xml, expected 'GameMode' node, got '%s'", modeXml->getTag());
				}
			}
		}
		else
		{
			CryLogAlways("CGameRulesModulesManager::Init(), invalid xml, expected 'Modes' node, got '%s'", root->getTag());
		}
	}
}
//------------------------------------------------------------------------
void CGameRulesHoldObjectiveBase::InitEffectData(XmlNodeRef xmlEffectNode)
{
	const int numChildren = xmlEffectNode->getChildCount();
	for(int childIdx=0; childIdx<numChildren; childIdx++)
	{
		XmlNodeRef xmlChild = xmlEffectNode->getChild(childIdx);
		if(!stricmp(xmlChild->getTag(), "ParticleEffect"))
		{
			const char* pParticleEffectName = NULL;
			if (xmlChild->getAttr("name", &pParticleEffectName))
			{
				m_effectData.pParticleEffect = gEnv->pParticleManager->FindEffect(pParticleEffectName, "CGameRulesHoldObjectiveBase");
				if(m_effectData.pParticleEffect)
				{
					m_effectData.pParticleEffect->AddRef();
				}
			}
			const char* pParticleGeomMaterialName = NULL;
			if (xmlChild->getAttr("particleGeomMaterial", &pParticleGeomMaterialName))
			{
				m_effectData.pParticleGeomMaterial = gEnv->p3DEngine->GetMaterialManager()->LoadMaterial(pParticleGeomMaterialName);
				if(m_effectData.pParticleGeomMaterial)
				{
					m_effectData.pParticleGeomMaterial->AddRef();
				}
			}
		}
		else if(!stricmp(xmlChild->getTag(), "RingEntity"))
		{
			const char* pRingEntityGeomName = NULL;
			if (xmlChild->getAttr("geom", &pRingEntityGeomName))
			{
				// Create ring effect entity
				SEntitySpawnParams ringSpawnParams;
				ringSpawnParams.pClass = gEnv->pEntitySystem->GetClassRegistry()->GetDefaultClass();
				ringSpawnParams.sName = "crashSiteRing";
				ringSpawnParams.nFlags = ENTITY_FLAG_NO_PROXIMITY | ENTITY_FLAG_CLIENT_ONLY | ENTITY_FLAG_NO_SAVE;
				IEntity* pRingEntity = gEnv->pEntitySystem->SpawnEntity(ringSpawnParams);
				if(pRingEntity)
				{
					pRingEntity->LoadGeometry(0,pRingEntityGeomName);
					pRingEntity->Hide(true);
					m_effectData.ringEntityID = pRingEntity->GetId();
				}
			}
		}
		else if(!stricmp(xmlChild->getTag(), "Params"))
		{
			float param = 0.0f;

			xmlChild->getAttr("alphaLerpSpeed", param);
			m_effectData.alphaLerp.SetLerpSpeed(param);

			xmlChild->getAttr("materialColorLerpSpeed", param);
			m_effectData.materialColorLerp.SetLerpSpeed(param);

			xmlChild->getAttr("particleColorLerpSpeed", param);
			m_effectData.particleColorLerp.SetLerpSpeed(param);

			xmlChild->getAttr("alphaFadeInDelayDuration", m_effectData.alphaFadeInDelayDuration);
			xmlChild->getAttr("particleEffectScale", m_effectData.particleEffectScale);
			xmlChild->getAttr("ringGeomScale", m_effectData.ringGeomScale);

			xmlChild->getAttr("friendlyColor", m_effectData.friendlyColor);
			xmlChild->getAttr("enemyColor", m_effectData.enemyColor);
			xmlChild->getAttr("neutralColor", m_effectData.neutralColor);
		}
	}

	SetNewEffectColor(eRPT_Neutral);
}
예제 #4
0
int CDialogLoader::LoadFromTable(XmlNodeRef tableNode, const string& groupName, TDialogScriptMap& outScriptMap)
{
	unsigned char nCellIndexToType[MAX_CELL_COUNT];
	memset(nCellIndexToType, ATTR_SKIP, sizeof(nCellIndexToType) );

	IMScript theScript;

	int nNumGoodScripts = 0;
 	int nRowIndex = 0;
	int nChilds = tableNode->getChildCount();
	for (int i=0; i<nChilds; ++i)
	{
		XmlNodeRef rowNode = tableNode->getChild(i);
		if (!rowNode || !rowNode->isTag("Row"))
			continue;

		++nRowIndex;

		// skip first row as it should only contain column description
		if (nRowIndex == 1)
		{
			FillMapping(rowNode, nCellIndexToType);
			continue;
		}

		IMScriptLine scriptLine;

		bool bLineValid = false;
		int nColCount = rowNode->getChildCount();
		int nCellIndex = 0;
		for (int j=0; j<nColCount; ++j)
		{
			XmlNodeRef cellNode = rowNode->getChild(j);
			if (!cellNode || !cellNode->isTag("Cell"))
				continue;

			int tmpIndex = 0;
			if (cellNode->getAttr("ss:Index", tmpIndex))
			{
				nCellIndex = tmpIndex-1;
			}

			if (nCellIndex < 0 || nCellIndex >= MAX_CELL_COUNT)
				break;

			XmlNodeRef cellDataNode = cellNode->findChild("Data");
			if (!cellDataNode)
			{
				++nCellIndex;
				continue;
			}

			unsigned char nCellType = nCellIndexToType[nCellIndex];

			const char* content = cellDataNode->getContent();

			// nRowIndex and nCellIndex should be correct now [1-based, not 0-based!]
			switch (nCellType)
			{
			case ATTR_SKIP:
				break;
			case ATTR_DIALOG:
				if (theScript.IsValid())
				{
					const bool ok = ProcessScript(theScript, groupName, outScriptMap);
					if (ok)
						++nNumGoodScripts;
					theScript.Reset();
				}
				theScript.name = content;
				break;
			case ATTR_ACTOR:
				scriptLine.actor = content;
				bLineValid = true;
				break;
			case ATTR_AUDIO:
				if (bLineValid)
				{
					if(content == 0)
						scriptLine.audioID = INVALID_AUDIO_CONTROL_ID;
					else
						gEnv->pAudioSystem->GetAudioTriggerID(content, scriptLine.audioID);
				}
				break;
			case ATTR_ANIM:
				if (bLineValid)
					scriptLine.anim = content;
				break;
			case ATTR_FACIAL:
				if (bLineValid)
				{
					size_t n = strcspn(content, ":; ");
					if (n == strlen(content))
					{
						scriptLine.facial = content;
						scriptLine.facialWeight = 0.5f;
						scriptLine.facialFadeTime = 0.5f;
					}
					else
					{
						scriptLine.facial.assign ( content, n );
						float w = 0.5f;
						float t = 0.5f;
						int nGood = sscanf(content+n+1, "%f%*[:; ]%f",&w,&t);
						if (nGood != 1 && nGood != 2)
						{
							GameWarning("[DIALOG] CDialogLoader::LoadFromTable: DialogScript '%s' has invalid Facial Expression Content '%s'. Using weight=%f fadetime=%f.", groupName.c_str(), content,w,t);
						}
						scriptLine.facialWeight = w;
						scriptLine.facialFadeTime = t;
					}
				}
				break;
			case ATTR_LOOKAT:
				if (bLineValid)
					scriptLine.lookat = content;
				break;
			case ATTR_DELAY:
				if (bLineValid)
				{
					float val = 0.0f;
					int n = sscanf(content,"%f", &val);
					if (n == 1)
					{
						scriptLine.delay = val;
					}
				}
				break;
			default:
				break;
			}

			++nCellIndex;
		}
		if (scriptLine.IsValid())
		{
			theScript.lines.push_back(scriptLine);
		}	
	}
	if (theScript.IsValid())
	{
		const bool ok = ProcessScript(theScript, groupName, outScriptMap);
		if (ok)
			++nNumGoodScripts;
	}

	return nNumGoodScripts;
}
예제 #5
0
void COptionsManager::ResetDefaults(const char* option)
{
	if(!m_pPlayerProfileManager)
		return;

	const char* user = m_pPlayerProfileManager->GetCurrentUser();
	IPlayerProfile *pProfile = m_pPlayerProfileManager->GetCurrentProfile(user);
	if(!pProfile)
		return;
	XmlNodeRef root = GetISystem()->LoadXmlFile("libs/config/profiles/default/attributes.xml");
	bool resetAll = (option==NULL);
	bool detectHardware = false;
	for (int i = 0; i < root->getChildCount(); ++i)
	{
		XmlNodeRef enumNameNode = root->getChild(i);
		const char *name = enumNameNode->getAttr("name");
		const char *value = enumNameNode->getAttr("value");
		if(name && value)
		{
			const char* attribCVar = "";
			bool bWriteToCfg = false;
			const bool bIsOption = IsOption(name, attribCVar, bWriteToCfg);
			if(bIsOption)
			{
				if(!resetAll && strcmp(attribCVar,option))
					continue;

				if(!strcmp(attribCVar, "sys_spec_Shadows"))
				{
					detectHardware = true;
				}

				if(!strcmp(attribCVar, "hud_colorLine"))
				{
					CryFixedStringT<32> color;
					color.Format("%d", g_pGameCVars->hud_colorLine);
					SetCrysisProfileColor(color.c_str());
				}

				if(!strcmp(attribCVar,"pb_client"))
				{
					if(atoi(value)==0)
					{
						m_pbEnabled = false;
						gEnv->pConsole->ExecuteString("net_pb_cl_enable false");
					}
					else
					{
						m_pbEnabled = true;
						gEnv->pConsole->ExecuteString("net_pb_cl_enable true");
					}
				}
				else if(!strcmp(attribCVar, "g_difficultyLevel"))
				{
					SetDifficulty(value);
				}
				else
				{
					ICVar *pCVar = gEnv->pConsole->GetCVar(attribCVar);
					if(pCVar)
					{
						pCVar->Set(value);
					}
				}
				if(!resetAll)
					break;
			}
		}
	}
	if(detectHardware)
		AutoDetectHardware("");
}
void CTeamVisualizationManager::InitTeamVisualizationData( XmlNodeRef xmlNode )
{
	if(m_teamVisualizationPartsMap.empty())
	{
		IMaterialManager *pMaterialManager = gEnv->p3DEngine->GetMaterialManager();

		// Parse Team vis data and add to m_teamVisualizationPartsMap; 
		XmlNodeRef pPlayerTeamVisualization = xmlNode->findChild("PlayerTeamVisualization");
		DesignerWarning(pPlayerTeamVisualization, "expected to find <PlayerTeamVisualization> </PlayerTeamVisualization>, not found");
		if(pPlayerTeamVisualization)
		{
			Crc32Gen* pCRCGen = gEnv->pSystem->GetCrc32Gen();

			// Grab each model setup node
			const int modelCount = pPlayerTeamVisualization->getChildCount();
			for(int i = 0; i < modelCount; ++i)
			{
				XmlNodeRef pModelSetup = pPlayerTeamVisualization->getChild(i);
				if(pModelSetup)
				{
					// Friendly 
					XmlNodeRef friendlyNode = pModelSetup->findChild("Friendly");
					DesignerWarning(friendlyNode, "missing <Friendly> </Friendly> tags in model setup <%d> - PlayerTeamVisualization.xml", i);
					if(friendlyNode)
					{
						// Hostile
						XmlNodeRef hostileNode = pModelSetup->findChild("Hostile");
						DesignerWarning(hostileNode, "missing <Hostile> </Hostile> tags in model setup <%d> - PlayerTeamVisualization.xml", i);
						if(hostileNode)
						{

							XmlNodeRef attachmentsNode = pModelSetup->findChild("BodyAttachments");
							const int numAttachments = attachmentsNode->getChildCount();
							DesignerWarning(attachmentsNode && numAttachments > 0, "missing <BodyAttachments> </bodyAttachments> tags in model setup <%d> or no child <BodyAttachment> elements - PlayerTeamVisualization.xml", i);
							if(attachmentsNode && numAttachments > 0)
							{
								const char* pModelName = pModelSetup->getAttr("name");
								DesignerWarning(pModelName && pModelName[0], "missing <Model> tag - or <Model name=""> attribute invalid - in model setup <%d> - PlayerTeamVisualization.xml", i);
								if(pModelName && pModelName[0])
								{
									// Add new + Fill in details
									TModelNameCRC modelNameCRC = pCRCGen->GetCRC32Lowercase(pModelName); 
									CRY_ASSERT(m_teamVisualizationPartsMap.find(modelNameCRC) == m_teamVisualizationPartsMap.end());
									m_teamVisualizationPartsMap[modelNameCRC] = SModelMaterialSetup(); 
									SModelMaterialSetup& newConfig = m_teamVisualizationPartsMap[modelNameCRC];

									// Get materials
									newConfig.SetMaterial(eMI_AliveFriendly, pMaterialManager->LoadMaterial(friendlyNode->getAttr("MaterialName")));
									newConfig.SetMaterial(eMI_AliveHostile, pMaterialManager->LoadMaterial(hostileNode->getAttr("MaterialName")));

									// Hostile
									XmlNodeRef deadFriendlyNode = pModelSetup->findChild("DeadFriendly");
									DesignerWarning(deadFriendlyNode, "missing <DeadFriendly> </DeadFriendly> tags in model setup <%d> - PlayerTeamVisualization.xml", i);
									if(deadFriendlyNode)
									{
										newConfig.SetMaterial(eMI_DeadFriendly, pMaterialManager->LoadMaterial(deadFriendlyNode->getAttr("MaterialName")));
									}

									XmlNodeRef deadHostileNode = pModelSetup->findChild("DeadHostile");
									DesignerWarning(deadHostileNode, "missing <deadHostileNode> </deadHostileNode> tags in model setup <%d> - PlayerTeamVisualization.xml", i);
									if(deadHostileNode)
									{
										newConfig.SetMaterial(eMI_DeadHostile, pMaterialManager->LoadMaterial(deadHostileNode->getAttr("MaterialName")));
									}

									// Attachments
									newConfig.m_attachments.reserve(numAttachments);
									for(int j = 0; j < numAttachments; ++j)
									{
										XmlNodeRef attachmentNode = attachmentsNode->getChild(j);
										newConfig.m_attachments.push_back(pCRCGen->GetCRC32Lowercase(attachmentNode->getAttr("name")));
									}	
									continue;
								}	
							}
						}
					}
				}
			}
		}
	}
}
TConnectionPtr CAudioSystemEditor_wwise::CreateConnectionFromXMLNode(XmlNodeRef pNode, EACEControlType eATLControlType)
{
    if (pNode)
    {
        const string sTag = pNode->getTag();
        TImplControlType type = TagToType(sTag);
        if (type != AUDIO_IMPL_INVALID_TYPE)
        {
            string sName = pNode->getAttr("wwise_name");
            string sLocalised = pNode->getAttr("wwise_localised");
            bool bLocalised = (sLocalised.compareNoCase("true") == 0);

            // If control not found, create a placeholder.
            // We want to keep that connection even if it's not in the middleware.
            // The user could be using the engine without the wwise project
            IAudioSystemControl* pControl = GetControlByName(sName, bLocalised);
            if (pControl == nullptr)
            {
                pControl = CreateControl(SControlDef(sName, type));
                if (pControl)
                {
                    pControl->SetPlaceholder(true);
                    pControl->SetLocalised(bLocalised);
                }
            }

            // If it's a switch we actually connect to one of the states within the switch
            if (type == eWCT_WWISE_SWITCH_GROUP || type == eWCT_WWISE_GAME_STATE_GROUP)
            {
                if (pNode->getChildCount() == 1)
                {
                    pNode = pNode->getChild(0);
                    if (pNode)
                    {
                        string sChildName = pNode->getAttr("wwise_name");

                        IAudioSystemControl* pChildControl = GetControlByName(sChildName, false, pControl);
                        if (pChildControl == nullptr)
                        {
                            pChildControl = CreateControl(SControlDef(sChildName, type == eWCT_WWISE_SWITCH_GROUP ? eWCT_WWISE_SWITCH : eWCT_WWISE_GAME_STATE, false, pControl));
                        }
                        pControl = pChildControl;
                    }
                }
                else
                {
                    CryWarning(VALIDATOR_MODULE_EDITOR, VALIDATOR_ERROR, "Audio Controls Editor (Wwise): Error reading connection to Wwise control %s", sName);
                }
            }

            if (pControl)
            {
                pControl->SetConnected(true);
                ++m_connectionsByID[pControl->GetId()];

                if (type == eWCT_WWISE_RTPC)
                {
                    switch (eATLControlType)
                    {
                    case EACEControlType::eACET_RTPC:
                    {
                        TRtpcConnectionPtr pConnection = std::make_shared<CRtpcConnection>(pControl->GetId());

                        float mult = 1.0f;
                        float shift = 0.0f;
                        if (pNode->haveAttr("atl_mult"))
                        {
                            const string sProperty = pNode->getAttr("atl_mult");
                            mult = (float)std::atof(sProperty.c_str());
                        }
                        if (pNode->haveAttr("atl_shift"))
                        {
                            const string sProperty = pNode->getAttr("atl_shift");
                            shift = (float)std::atof(sProperty.c_str());
                        }
                        pConnection->fMult = mult;
                        pConnection->fShift = shift;
                        return pConnection;
                    }
                    case EACEControlType::eACET_SWITCH_STATE:
                    {
                        TStateConnectionPtr pConnection = std::make_shared<CStateToRtpcConnection>(pControl->GetId());

                        float value = 0.0f;
                        if (pNode->haveAttr("atl_mult"))
                        {
                            const string sProperty = pNode->getAttr("wwise_value");
                            value = (float)std::atof(sProperty.c_str());
                        }
                        pConnection->fValue = value;
                        return pConnection;
                    }
                    }
                }
                else
                {
                    return std::make_shared<IAudioConnection>(pControl->GetId());
                }
            }
        }
    }
    return nullptr;
}
void CHUDMissionObjectiveSystem::LoadLevelObjectivesInternal(const char* levelpath)
{
	CryFixedStringT<128> filename;
	if (levelpath==NULL)
	{
		// there is no Objectives_global.xml, but there is a file with the previous standard naming
		// load the file with old name for backwards compatibility
		if (!gEnv->pCryPak->IsFileExist("Libs/UI/Objectives_global.xml")
			&& gEnv->pCryPak->IsFileExist("Libs/UI/Objectives_new.xml"))
		{
			CryWarning(VALIDATOR_MODULE_GAME, VALIDATOR_WARNING, "File 'Objectives_new.xml' is deprecated and should be renamed to 'Objectives_global.xml'");
			filename = "Libs/UI/Objectives_new.xml";
		}
		else
		{
			filename = "Libs/UI/Objectives_global.xml";
		}
	}
	else
	{
		filename.Format("%s/leveldata/Objectives.xml", levelpath);
	}
	/*if(gEnv->bMultiplayer)
	{
		CGameRules *pGameRules = g_pGame->GetGameRules();
		if(stricmp (pGameRules->GetEntity()->GetClass()->GetName(), "Coop"))
			filename = "Libs/UI/MP_Objectives.xml";
	}*/

	XmlNodeRef missionObjectives = GetISystem()->LoadXmlFromFile(filename.c_str());
	if (missionObjectives == 0)
		return;

	for(int tag = 0; tag < missionObjectives->getChildCount(); ++tag)
	{
		XmlNodeRef mission = missionObjectives->getChild(tag);
		const char* attrib;
		const char* objective;
		const char* text;
		const char* optional;

		const char* levelName;
		if (!mission->getAttr("name", &levelName))
		{
			levelName = mission->getTag();
		}

		for(int obj = 0; obj < mission->getChildCount(); ++obj)
		{
			XmlNodeRef objectiveNode = mission->getChild(obj);
			string id(levelName);
			id.append(".");
			id.append(objectiveNode->getTag());
			if(objectiveNode->getAttributeByIndex(0, &attrib, &objective) && objectiveNode->getAttributeByIndex(1, &attrib, &text))
			{
				bool secondaryObjective = false;
				int attribs = objectiveNode->getNumAttributes();
				for(int attribIndex = 2; attribIndex < attribs; ++attribIndex)
				{
					if(objectiveNode->getAttributeByIndex(attribIndex, &attrib, &optional))
					{
						if(attrib)
						{
							if(!stricmp(attrib, "Secondary"))
							{
								if(!stricmp(optional, "true"))
									secondaryObjective = true;
							}
						}
					}
				}
				m_currentMissionObjectives.push_back(CHUDMissionObjective(this, id.c_str(), objective, text, secondaryObjective));
			}
			else
				GameWarning("Error reading mission objectives.");
		}
	}
}
예제 #9
0
// Load an equipment pack from an XML node
bool CEquipmentManager::LoadEquipmentPack(const XmlNodeRef& rootNode, bool bOverrideExisting)
{
	if (rootNode->isTag("EquipPack") == false)
		return false;

	const char* packName = rootNode->getAttr("name");
	const char* primaryName = rootNode->getAttr("primary");

	if (!packName || packName[0] == 0)
		return false;

	// re-use existing pack
	SEquipmentPack* pPack = GetPack(packName);
	if (pPack == 0)
	{
		pPack = new SEquipmentPack;
		m_equipmentPacks.push_back(pPack);
	}
	else if (bOverrideExisting == false)
		return false;

	pPack->Init(packName);

	for (int iChild=0; iChild<rootNode->getChildCount(); ++iChild)
	{
		const XmlNodeRef childNode = rootNode->getChild(iChild);
		if (childNode == 0)
			continue;

		if (childNode->isTag("Items"))
		{
			pPack->PrepareForItems(childNode->getChildCount());
			for (int i=0; i<childNode->getChildCount(); ++i)
			{
				XmlNodeRef itemNode = childNode->getChild(i);
				const char* itemName = itemNode->getTag();
				const char* itemType = itemNode->getAttr("type");
				const char* itemSetup = itemNode->getAttr("setup");
				pPack->AddItem(itemName, itemType, itemSetup);
			}
		}
		else if (childNode->isTag("Ammo")) // legacy
		{
			const char *ammoName = "";
			const char *ammoCount = "";
			int nAttr = childNode->getNumAttributes();
			for (int j=0; j<nAttr; ++j)
			{
				if (childNode->getAttributeByIndex(j, &ammoName, &ammoCount))
				{
					int nAmmoCount = atoi(ammoCount);
					pPack->m_ammoCount[ammoName] = nAmmoCount;
				}
			}
		}
		else if (childNode->isTag("Ammos"))
		{
			for (int i=0; i<childNode->getChildCount(); ++i)
			{
				XmlNodeRef ammoNode = childNode->getChild(i);
				if (ammoNode->isTag("Ammo") == false)
					continue;
				const char* ammoName = ammoNode->getAttr("name");
				if (ammoName == 0 || ammoName[0] == '\0')
					continue;
				int nAmmoCount = 0;
				ammoNode->getAttr("amount", nAmmoCount);
				pPack->m_ammoCount[ammoName] = nAmmoCount;
			}
		}
	}
	// assign primary.
	if (pPack->HasItem(primaryName))
		pPack->m_primaryItem = primaryName;
	else
		pPack->m_primaryItem = "";

	return true;
}
예제 #10
0
void CAntiCheatManager::ParseAntiCheatConfig(XmlNodeRef xmlData)
{
	ResetAntiCheatVars();

	// Reset the previous configuration so that we can call this function multiple times
	for (int i=0; i<eCT_Num; ++i)
	{
		m_cheats[i].actions.clear();
	}
	m_globalActions.clear();
	m_assetGroupWeights.clear();
	m_assetGroupWeights.resize(eAG_Num);
	m_totalAssetWeighting = 0;
	m_fileProtectConfig = NULL;

	int numChildren = xmlData->getChildCount();
	for (int i=0; i<numChildren; ++i)
	{
		XmlNodeRef child = xmlData->getChild(i);
		if (child->isTag("Cheat"))
		{
			int numActions = child->getChildCount();
			const char* sTypeName = child->getAttr("type");
			TCheatType cheatType = FindCheatType(sTypeName);
			if (cheatType != eCT_Invalid)
			{
				SCheatType &cheat = m_cheats[cheatType];
				cheat.actions.reserve(numActions);
				for (int j=0; j<numActions; ++j)
				{
					XmlNodeRef actionChild = child->getChild(j);
					if (actionChild->isTag("Action"))
					{
						bool addAction = true;
						int numConditions = actionChild->getChildCount();
						SCheatAction cheatAction;
						const char* sActionName = actionChild->getAttr("value");
						cheatAction.action = FindCheatAction(sActionName);
						if (cheatAction.action != eCA_Invalid)
						{
							int nConfidence = kDefaultConfidence;
							actionChild->getAttr("confidence", nConfidence);

							cheatAction.confidence = nConfidence;

							if (cheatAction.action == eCA_Infraction)
							{
								actionChild->getAttr("severity", cheatAction.severity);
								if (cheatAction.severity <= 0.f)
								{
									CryLog("Invalid severity %f", cheatAction.severity);
									cheatAction.severity = 0.f;
								}
							}
							else if (cheatAction.action == eCA_Ban)
							{
								actionChild->getAttr("timeout", cheatAction.banTimeout);
							}
							cheatAction.conditions.reserve(numConditions);
							for (int k=0; k<numConditions; ++k)
							{
								XmlNodeRef conditionChild = actionChild->getChild(k);
								if (conditionChild->isTag("Condition"))
								{
									SCheatCondition cheatCondition;
									const char* sOperatorName = conditionChild->getAttr("operator");
									cheatCondition.op = FindCheatOperator(sOperatorName);
									if (cheatCondition.op != eCO_Invalid)
									{
										conditionChild->getAttr("value", cheatCondition.value);
										conditionChild->getAttr("param", cheatCondition.paramNum);
										cheatAction.conditions.push_back(cheatCondition);
									}
									else
									{
										CryLog("Unrecognised operator %s", sOperatorName);
									}
								}
								else if (conditionChild->isTag("DediVersion"))
								{
#if defined(DEDICATED_SERVER)
									const char* sOperatorName = conditionChild->getAttr("operator");
									ECheatOperator op = FindCheatOperator(sOperatorName);
									if (op != eCO_Invalid)
									{
										int value;
										if (conditionChild->getAttr("value", value))
										{
											if (!MeetsCondition(op, DEDI_VERSION, value))
											{
												// Ignore this action if it doesn't meet the gamespy dedi version check
												addAction = false;
												break;
											}
										}
									}
									else
									{
										CryLog("Unrecognised operator %s", sOperatorName);
									}
#endif
								}
								else
								{
									CryLog("Unrecognised child node %s", conditionChild->getTag());
								}
							}
							if (addAction)
							{
								cheat.actions.push_back(cheatAction);
							}
						}
						else
						{
							CryLog("Unrecognised action %s", sActionName);
						}
					}
					else
					{
						CryLog("Unrecognised child node %s", actionChild->getTag());
					}
				}
			}
			else
			{
				CryLog("Unrecognised cheat type %s", sTypeName);
			}
		}
		else if (child->isTag("Global"))
		{
			child->getAttr("decay_rate", m_decayRate);
			int numActions = child->getChildCount();
			m_globalActions.reserve(numActions);
			for (int j=0; j<numActions; ++j)
			{
				XmlNodeRef actionChild = child->getChild(j);
				if (actionChild->isTag("Action"))
				{
					SGlobalCheatAction cheatAction;
					const char* sActionName = actionChild->getAttr("value");
					cheatAction.action = FindCheatAction(sActionName);
					if (cheatAction.action != eCA_Invalid)
					{
						if (cheatAction.action == eCA_Ban)
						{
							actionChild->getAttr("timeout", cheatAction.banTimeout);
						}
						actionChild->getAttr("threshhold", cheatAction.threshhold);
						if (cheatAction.threshhold > 0.f)
						{
							m_globalActions.push_back(cheatAction);
						}
						else
						{
							CryLog("Invalid threshhold %f", cheatAction.threshhold);
						}
					}
					else
					{
						CryLog("Unrecognised action %s", sActionName);
					}
				}
				else
				{
					CryLog("Unrecognised child node %s", actionChild->getTag());
				}
			}
		}
		else if (child->isTag("DataProbe"))
		{
			child->getAttr("hash_method", m_hashMethod);
			int numChildren = child->getChildCount();
			for ( int groupidx = 0; groupidx < numChildren; ++groupidx )
			{
				XmlNodeRef groupChild = child->getChild(groupidx);
				if (groupChild->isTag("Asset"))
				{
					const char* sGroupExtName = groupChild->getAttr("ext");
					TCheatAssetGroup assetGroup = FindAssetTypeByExtension(sGroupExtName);
					if (assetGroup != eAG_Invalid )
					{
						int weight = 0;
						if ( groupChild->getAttr("weight",weight) )
						{
							m_totalAssetWeighting += m_assetGroupWeights[assetGroup] = weight;
						}
						else
						{
							CryLog("Extension had no weighting %s", sGroupExtName);
						}
					}
					else
					{
						CryLog("Unrecognised extension %s", sGroupExtName);
					}
				}
				else if (groupChild->isTag("protect"))
				{
					m_fileProtectConfig = groupChild;
				}
				else
				{
					CryLog("Unrecognised child node %s", groupChild->getTag());
				}
			}
		}
		else if (child->isTag("AntiCheatVars"))
		{
			LoadAntiCheatVars(child);
		}
		else
		{
			CryLog("Unrecognised child node %s", child->getTag());
		}
	}
}
예제 #11
0
void CDataPatchDownloader::ApplyCVarPatch()
{
	// Open the file regardless of whether or not we're going to use it - makes sure the file is in the MP mode
	// switch pak
  FILE * f = gEnv->pCryPak->FOpen( "Scripts/DataPatcher/patchablecvars.txt", "rt" );
  if (!f)
	{
		// Failed to open whitelist - don't patch any cvars
    return;
	}

	if (m_patchingEnabled)
	{
		AssertPatchDownloaded();

		if (m_patchXML)
		{
			std::vector<string> cvarsWhiteList;
			cvarsWhiteList.reserve(64);

			// Parse the cvars white list - code taken from CVarListProcessor.cpp

		  const int BUFSZ = 4096;
		  char buf[BUFSZ];

		  size_t nRead;
		  string cvar;
		  bool comment = false;
		  do
		  {
				cvar.resize(0);
				buf[0]='\0';
		    nRead = gEnv->pCryPak->FRead( buf, BUFSZ, f );

		    for (size_t i=0; i<nRead; i++)
		    {
		      char c = buf[i];
		      if (comment)
		      {
		        if (c == '\r' || c == '\n')
		          comment = false;
		      }
		      else
		      {
		        if (c == '_' || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || (c == '.'))
		        {
		          cvar += c;
		        }
		        else if (c == '\t' || c == '\r' || c == '\n' || c == ' ')
		        {
		          if (ICVar * pV = gEnv->pConsole->GetCVar(cvar.c_str()))
							{
								cvarsWhiteList.push_back(cvar);
							}
		          cvar.resize(0);
		        }
		        else if (c == '#')
		        {
		          comment = true;
		        }
		      }
		    }
		  }
		  while (nRead != 0);

			// Now apply the patch
			const int numAllowedCVars = cvarsWhiteList.size();

			const int numChildren = m_patchXML->getChildCount();
			for (int i = 0; i < numChildren; i ++)
			{
				XmlNodeRef xmlChild = m_patchXML->getChild(i);

				if (xmlChild->isTag("cvarpatch"))
				{
					const int numCVars = xmlChild->getChildCount();

					const char *pCVar = NULL;
					const char *pValue = NULL;

					for (int cvarIndex = 0; cvarIndex < numCVars; ++ cvarIndex)
					{
						XmlNodeRef xmlCVar = xmlChild->getChild(cvarIndex);
						
						if (xmlCVar->isTag("cvar"))
						{
							if (xmlCVar->getAttr("name", &pCVar) && xmlCVar->getAttr("value", &pValue))
							{
								bool bAllowed = false;

								for (int allowedIndex = 0; allowedIndex < numAllowedCVars; ++ allowedIndex)
								{
									string &allowedCVar = cvarsWhiteList[allowedIndex];
									if (!stricmp(allowedCVar.c_str(), pCVar))
									{
										bAllowed = true;
										break;
									}
								}

								if (bAllowed)
								{
									CryLog("ApplyCVarPatch() patching cvar '%s' to '%s'", pCVar, pValue);
									g_pGame->GetGameModeCVars().ApplyAndStoreCVar(pCVar, pValue);
								}
								else
								{
									CryLog("ApplyCVarPatch() cvar '%s' not allowed - ignoring", pCVar);
								}
							}
						}
					}

					break;
				}
			}
		}
	}

	gEnv->pCryPak->FClose( f );
}
//--------------------------------------------------------------------------------------------------
// Name: CFrontEndModelCache
// Desc: Constructor
//--------------------------------------------------------------------------------------------------
CFrontEndModelCache::CFrontEndModelCache()
{
#if FEMC_USE_LEVEL_HEAP
	SwitchToLevelHeap();
#endif // #if FEMC_USE_LEVEL_HEAP

	FE_LOG("Front End model cache creation");
	INDENT_LOG_DURING_SCOPE();

	IGameFramework* pGameFramework = g_pGame->GetIGameFramework();
	if(pGameFramework)
	{
		pGameFramework->StartNetworkStallTicker(true);
	}

	m_bIsMultiplayerCache = gEnv->bMultiplayer;

#if FEMC_FILE_ACCESS_LOG
	gEnv->pConsole->GetCVar("sys_FileAccessLog")->Set(1);
#endif // #if FEMC_FILE_ACCESS_LOG

#ifdef FEMC_LOG_CACHE_TIME
	const float startTime = gEnv->pTimer->GetAsyncCurTime();
#endif // #ifdef FEMC_LOG_CACHE_TIME

#if FEMC_CACHE_FILE_ACCESSES
	if (g_pGameCVars->g_FEMenuCacheSaveList)
	{
		gEnv->pCryPak->RegisterFileAccessSink(this);
		m_recordedFiles.clear();
	}
	int oldSaveLevelResourceList = 0;
	ICVar* pPakSaveLevelResourceListCvar = gEnv->pConsole->GetCVar("sys_PakSaveLevelResourceList");
	if(pPakSaveLevelResourceListCvar)
	{
		oldSaveLevelResourceList = pPakSaveLevelResourceListCvar->GetIVal();
		pPakSaveLevelResourceListCvar->Set(0);
	}
	m_pReasonForReportingFileOpen = "CFrontEndModelCache constructor";
#endif // #if FEMC_CACHE_FILE_ACCESSES

	CRY_ASSERT(s_pSingletonInstance == NULL);
	s_pSingletonInstance = this;

	// Load model list from xml, and cache each entry
	XmlNodeRef pRootNode = gEnv->pSystem->LoadXmlFromFile(FEMC_CACHE_LIST_FILENAME);
	if(pRootNode)
	{
		CGameXmlParamReader xmlParamReader(pRootNode);
		const char* pPakName = NULL;

		// Pak
		const char* const pGameFolder = gEnv->pCryPak->GetGameFolder();
		const XmlNodeRef pPakData = xmlParamReader.FindFilteredChild("PakData");
		if(pPakData && pPakData->getChildCount())
		{
			const XmlNodeRef pPak = pPakData->getChild(0);
			if(pPak)
			{
				pPakName = pPak->getAttr("name");
				bool bSucceeded = gEnv->pCryPak->OpenPack(pGameFolder,pPakName,ICryPak::FLAGS_FILENAMES_AS_CRC32);
				bSucceeded |= gEnv->pCryPak->LoadPakToMemory(pPakName,ICryPak::eInMemoryPakLocale_GPU);
				FE_LOG ("%s to open pack file '%s' bound to %s", bSucceeded ? "Managed" : "Failed", pPakName, pGameFolder);
			}

			// There is a pak, so reserve space for some materials in cache
			const uint materialCacheReserve = 64;
			m_materialCache.reserve(materialCacheReserve);
		}

		// Cache character models
		const XmlNodeRef pCharacterModelList = xmlParamReader.FindFilteredChild("CharacterModels");
		if(pCharacterModelList)
		{
			const int characterModelCount = pCharacterModelList->getChildCount();
			if(characterModelCount)
			{
				CreateSupportForFrontEnd3dModels();
			}

			for(int i=0; i<characterModelCount; i++)
			{
				const XmlNodeRef pCharacterModel = pCharacterModelList->getChild(i);
				if(pCharacterModel)
				{
					const char* pCharacterModelName = pCharacterModel->getAttr("name");
					CacheCharacterModel(pCharacterModelName);
				}
			}
		}

		// Cache item models
		const XmlNodeRef pItemModelsList = xmlParamReader.FindFilteredChild("ItemModels");
		if(pItemModelsList)
		{
			const int itemModelCount = pItemModelsList->getChildCount();
			if(itemModelCount)
			{
				CreateSupportForFrontEnd3dModels();
			}

			for(int i=0; i<itemModelCount; i++)
			{
				const XmlNodeRef pItemModel = pItemModelsList->getChild(i);
				if(pItemModel)
				{
					const char* pItemModelName = pItemModel->getAttr("name");
					if (strcmp(pItemModel->getTag(), "GeometryModels") == 0)
					{
						m_myGeometryCache.CacheGeometry(pItemModelName, false, IStatObj::ELoadingFlagsIgnoreLoDs);
					}
					else if (strcmp(pItemModel->getTag(), "ItemModel") == 0)
					{
						CacheItemModel(pItemModelName);
					}
				}
			}
		}

		// Unload pak
		if(pPakName)
		{
			gEnv->pCryPak->LoadPakToMemory( pPakName,ICryPak::eInMemoryPakLocale_Unload );
			bool bSucceeded = gEnv->pCryPak->ClosePack( pPakName,0 );
			FE_LOG ("%s to close pack file '%s'", bSucceeded ? "Managed" : "Failed", pPakName);
		}
	}

#if FEMC_FILE_ACCESS_LOG
	gEnv->pConsole->GetCVar("sys_FileAccessLog")->Set(0);
#endif // #if FEMC_FILE_ACCESS_LOG
#ifdef FEMC_LOG_CACHE_TIME
	const float endTime = gEnv->pTimer->GetAsyncCurTime();
	const float deltaTime = endTime - startTime;
	FE_LOG("FrontEndModelCache loading took %3.1f seconds", deltaTime);
#endif // #FEMC_LOG_CACHE_TIME FE_MODEL_CACHE_LOG_CACHE_TIME
#if FEMC_CACHE_FILE_ACCESSES
	m_pReasonForReportingFileOpen = NULL;

	if (g_pGameCVars->g_FEMenuCacheSaveList)
	{
		// To stop any other threads from messing
		gEnv->pCryPak->UnregisterFileAccessSink(this);

		std::set<string> fileset;
		// eliminate duplicate values
		std::vector<string>::iterator endLocation = std::unique( m_recordedFiles.begin(),m_recordedFiles.end() );
		m_recordedFiles.erase( endLocation,m_recordedFiles.end() );

		fileset.insert( m_recordedFiles.begin(),m_recordedFiles.end() );

		string sResourceSetFilename = PathUtil::AddSlash("Levels/Multiplayer") + "mpmenu_list.txt";
		{
			FILE* pFile = fxopen(sResourceSetFilename,"wb",true);
			if(pFile)
			{
				for(std::set<string>::iterator it = fileset.begin(); it != fileset.end(); ++it)
				{
					const char *pStr = it->c_str();
					fprintf( pFile,"%s\n",pStr );
					// Automatically add cgf->cgfm, cga->cgam, dds->dds.0
					const char* const pExt = PathUtil::GetExt(pStr);
					if (strcmp(pExt, "cgf") == 0)
					{
						fprintf( pFile,"%sm\n",pStr );
					}
					else if (strcmp(pExt, "cga") == 0)
					{
						fprintf( pFile,"%sm\n",pStr );
					}
					else if (strcmp(pExt, "dds") == 0)
					{
						fprintf( pFile,"%s.0\n",pStr );
					}
				}
				fclose(pFile);
			}
		}
	}
	if(pPakSaveLevelResourceListCvar)
	{
		pPakSaveLevelResourceListCvar->Set(oldSaveLevelResourceList);
	}
#endif // #if FEMC_CACHE_FILE_ACCESSES

	if(pGameFramework)
	{
		pGameFramework->StopNetworkStallTicker();
	}

	FE_LOG("Done caching items for front end");

#if FEMC_USE_LEVEL_HEAP
	SwitchToGlobalHeap();
#endif // #if FEMC_USE_LEVEL_HEAP
}//-------------------------------------------------------------------------------------------------
//------------------------------------------------------------------------
void CGameRulesKingOfTheHillObjective::Init( XmlNodeRef xml )
{
	BaseType::Init(xml);

	if (xml->getAttr("scoreTime", m_scoreTimerMaxLength))
	{
		CryLog("CGameRulesKingOfTheHillObjective::Init, using score timer, length=%f", m_scoreTimerMaxLength);
	}
	xml->getAttr("additionalPlayerTimerMultiplier", m_scoreTimerAdditionalPlayerMultiplier);
	if (m_scoreTimerAdditionalPlayerMultiplier == 0.f)
	{
		m_scoreTimerAdditionalPlayerMultiplier = 1.f;
	}
	CryLog("CGameRulesKingOfTheHillObjective::Init, multiplier for additional players=%f", m_scoreTimerAdditionalPlayerMultiplier);

	int numChildren = xml->getChildCount();
	for (int childIdx = 0; childIdx < numChildren; ++ childIdx)
	{
		XmlNodeRef xmlChild = xml->getChild(childIdx);
		const char *pTag = xmlChild->getTag();
		if (!stricmp(pTag, "Icons"))
		{
			CRY_ASSERT_MESSAGE(!m_useIcons, "KingOfTheHillObjective xml contains more than one 'Icons' node, we only support one");
			m_useIcons = true;

			m_neutralIcon   = SGameRulesMissionObjectiveInfo::GetIconId(xmlChild->getAttr("neutral"));
			m_friendlyIcon  = SGameRulesMissionObjectiveInfo::GetIconId(xmlChild->getAttr("friendly"));
			m_hostileIcon   = SGameRulesMissionObjectiveInfo::GetIconId(xmlChild->getAttr("hostile"));
			m_contestedIcon = SGameRulesMissionObjectiveInfo::GetIconId(xmlChild->getAttr("contested"));

			m_shouldShowIconFunc.Format("%s", xmlChild->getAttr("checkFunc"));

			CryLog("CGameRulesKingOfTheHillObjective::Init, using on-screen icons [%i %i %i %i]", m_neutralIcon, m_friendlyIcon, m_hostileIcon, m_contestedIcon);
		}
		else if(strcmp(pTag,"Audio") == 0)
		{
			if(xmlChild->haveAttr("capturedLoop"))
			{
				m_captureSignalId = g_pGame->GetGameAudio()->GetSignalID(xmlChild->getAttr("capturedLoop"));
			}
		}
		else if (!stricmp(pTag, "Strings"))
		{
			const char *pString = 0;
			if (xmlChild->getAttr("friendlyCapture", &pString))
			{
				m_friendlyCaptureString.Format("@%s", pString);
			}
			if (xmlChild->getAttr("enemyCapture", &pString))
			{
				m_enemyCaptureString.Format("@%s", pString);
			}
			if (xmlChild->getAttr("friendlyLost", &pString))
			{
				m_friendlyLostString.Format("@%s", pString);
			}
			if (xmlChild->getAttr("enemyLost", &pString))
			{
				m_enemyLostString.Format("@%s", pString);
			}
			if (xmlChild->getAttr("newEntity", &pString))
			{
				m_newEntityString.Format("@%s", pString);
			}
			if (xmlChild->getAttr("gameStateNeutral", &pString))
			{
				m_gameStateNeutralString.Format("@%s", pString);
			}
			if (xmlChild->getAttr("gameStateFriendly", &pString))
			{
				m_gameStateFriendlyString.Format("@%s", pString);
			}
			if (xmlChild->getAttr("gameStateEnemy", &pString))
			{
				m_gameStateEnemyString.Format("@%s", pString);
			}
			if (xmlChild->getAttr("gameStateDestructing", &pString))
			{
				m_gameStateDestructingString.Format("@%s", pString);
			}
			if (xmlChild->getAttr("gameStateIncoming", &pString))
			{
				m_gameStateIncomingString.Format("@%s", pString);
			}
			if (xmlChild->getAttr("iconTextDefend", &pString))
			{
				m_iconTextDefend.Format("@%s", pString);
				m_iconTextDefend = CHUDUtils::LocalizeString(m_iconTextDefend.c_str());
			}
			if (xmlChild->getAttr("iconTextClear", &pString))
			{
				m_iconTextClear.Format("@%s", pString);
				m_iconTextClear = CHUDUtils::LocalizeString(m_iconTextClear.c_str());
			}
			if (xmlChild->getAttr("iconTextCapture", &pString))
			{
				m_iconTextCapture.Format("@%s", pString);
				m_iconTextCapture = CHUDUtils::LocalizeString(m_iconTextCapture.c_str());
			}
		}
		else if (!stricmp(pTag, "RadiusPulse"))
		{
			xmlChild->getAttr("time", m_pulseTimerLength);
			m_shouldDoPulseEffectFunc.Format("%s", xmlChild->getAttr("checkFunc"));
		}
	}
}
void CForceFeedBackSystem::LoadEffects( XmlNodeRef& effectsNode )
{
	CGameXmlParamReader paramReader(effectsNode);
	const int effectsCount = paramReader.GetUnfilteredChildCount();

	m_effectToIndexMap.reserve(effectsCount);
	m_effects.reserve(effectsCount);
	m_effectNames.reserve(effectsCount);

	for (int i = 0; i < effectsCount; ++i)
	{
		XmlNodeRef childEffectNode = paramReader.GetFilteredChildAt(i);

		if( childEffectNode )
		{
			SEffect newEffect;
			const int effectDataCount = childEffectNode->getChildCount();

			const char* effectName = childEffectNode->getAttr("name");

			//Check for invalid name
			if ((effectName == NULL) || (effectName[0] == '\0'))
			{
				FORCEFEEDBACK_LOG("Could not load effect without name (at line %d)", childEffectNode->getLine());
				continue;
			}

			//Check for duplicates
			if (m_effectToIndexMap.find(FFBInternalId::GetIdForName(effectName)) != m_effectToIndexMap.end())
			{
				FORCEFEEDBACK_LOG("Effect '%s' does already exists, skipping", effectName);
				continue;
			}

			childEffectNode->getAttr("time", newEffect.time);	

			for (int j = 0; j < effectDataCount; ++j)
			{
				XmlNodeRef motorNode = childEffectNode->getChild(j);

				const char* motorTag = motorNode->getTag();

				if (strcmp(motorTag, "MotorAB") == 0)
				{
					newEffect.patternA.Set( motorNode->haveAttr("pattern") ? motorNode->getAttr("pattern") : "" );
					newEffect.patternB = newEffect.patternA;
					newEffect.envelopeA.Set( motorNode->haveAttr("envelope") ? motorNode->getAttr("envelope") : "" );
					newEffect.envelopeB = newEffect.envelopeA;
					motorNode->getAttr("frequency", newEffect.frequencyA);
					newEffect.frequencyB = newEffect.frequencyA;
				}
				else if (strcmp(motorTag, "MotorA") == 0)
				{
					newEffect.patternA.Set( motorNode->haveAttr("pattern") ? motorNode->getAttr("pattern") : "" );
					newEffect.envelopeA.Set( motorNode->haveAttr("envelope") ? motorNode->getAttr("envelope") : "" );
					motorNode->getAttr("frequency", newEffect.frequencyA);
				}
				else if (strcmp(motorTag, "MotorB") == 0)
				{
					newEffect.patternB.Set( motorNode->haveAttr("pattern") ? motorNode->getAttr("pattern") : "" );
					newEffect.envelopeB.Set( motorNode->haveAttr("envelope") ? motorNode->getAttr("envelope") : "" );
					motorNode->getAttr("frequency", newEffect.frequencyB);
				}
			}

			newEffect.frequencyA = (float)__fsel(-newEffect.frequencyA, 1.0f, newEffect.frequencyA);
			newEffect.frequencyB = (float)__fsel(-newEffect.frequencyB, 1.0f, newEffect.frequencyB);

			m_effects.push_back(newEffect);
			m_effectNames.push_back(effectName);

			FFBInternalId internalId;
			internalId.Set(effectName);
			m_effectToIndexMap.insert(TEffectToIndexMap::value_type(internalId, ((int)m_effects.size() - 1)));
		}
	}
}
예제 #15
0
void CClientHitEffectsMP::ProcessEffectInfo(SHitEffectInfoSet& hitEffectSet, XmlNodeRef xmlNode, const char* libraryName)
{
    bool foundDefault = false;
    bool foundMelee = false;
    const uint numEffects = xmlNode->getChildCount();
    IMaterialEffects* pMaterialEffects = gEnv->pMaterialEffects;
    IEntityClassRegistry* pClassRegistry = gEnv->pEntitySystem->GetClassRegistry();

    hitEffectSet.m_effectInfos.reserve(numEffects);

    for (uint i = 0; i < numEffects; i++)
        {
            if(XmlNodeRef childNode = xmlNode->getChild(i))
                {
                    if(const char* nameTag = childNode->getTag())
                        {
                            if(!foundDefault && !strcmp("default", nameTag))
                                {
                                    const char* effectName = childNode->getAttr("effect");

                                    if(effectName)
                                        {
                                            hitEffectSet.m_default = pMaterialEffects->GetEffectIdByName(libraryName, effectName);
                                        }

                                    foundDefault = true;
                                }
                            else if(!foundMelee && !strcmp("melee", nameTag))
                                {
                                    const char* effectName = childNode->getAttr("effect");

                                    if(effectName)
                                        {
                                            hitEffectSet.m_melee = pMaterialEffects->GetEffectIdByName(libraryName, effectName);
                                        }

                                    foundMelee = true;
                                }
                            else
                                {
                                    SHitEffectInfo newInfo;

                                    newInfo.pAmmoClass = pClassRegistry->FindClass(nameTag);

                                    const char* effectName = childNode->getAttr("effect");

                                    if(effectName)
                                        {
                                            newInfo.effectId = pMaterialEffects->GetEffectIdByName(libraryName, effectName);
                                        }

                                    if(newInfo.pAmmoClass && newInfo.effectId)
                                        {
                                            hitEffectSet.m_effectInfos.push_back(newInfo);
                                        }
                                    else
                                        {
                                            if(!newInfo.pAmmoClass)
                                                {
                                                    GameWarning("Class type %s does not exist", nameTag);
                                                }

                                            if(!newInfo.effectId)
                                                {
                                                    GameWarning("Material Effect %s does not exist", effectName ? effectName : "");
                                                }
                                        }
                                }
                        }
                }
        }

    if(!hitEffectSet.m_melee)
        {
            hitEffectSet.m_melee = hitEffectSet.m_default;
        }
}
//======================================================================
void CWeaponAttachmentManager::CreatePlayerBoneAttachments()
{
	if (ICharacterInstance *pCharInstance = m_pOwner->GetEntity()->GetCharacter(0))
	{
		IAttachmentManager *pAttachmentManager = pCharInstance->GetIAttachmentManager();

		if(pAttachmentManager == NULL)
		{
			return;
		}

		const XmlNodeRef rootNode = gEnv->pSystem->LoadXmlFromFile( WEAPON_ATTACHMENTS_FILE );

		if (!rootNode || strcmpi(rootNode->getTag(), "WeaponAttachments"))
		{
			CryWarning(VALIDATOR_MODULE_GAME, VALIDATOR_WARNING, "Could not load Weapon Attachments data. Invalid XML file '%s'! ", WEAPON_ATTACHMENTS_FILE);
			return;
		}

		IAttachment *pAttachment = NULL;
		const int childCount = rootNode->getChildCount();

		for (int i = 0; i < childCount; ++i)
		{
			XmlNodeRef weaponAttachmentNode = rootNode->getChild(i);

			if(weaponAttachmentNode == (IXmlNode *)NULL)
			{
				continue;
			}

			const char *attachmentName = "";
			weaponAttachmentNode->getAttr("name", &attachmentName);

			if(!strcmp(attachmentName, ""))
			{
				CryWarning(VALIDATOR_MODULE_GAME, VALIDATOR_WARNING, "Empty Weapon Attachment name in file: %s! Skipping Weapon Attachment.", WEAPON_ATTACHMENTS_FILE);
				continue;
			}

			pAttachment = pAttachmentManager->GetInterfaceByName(attachmentName);

			if(pAttachment)
			{
				continue;
			}

			//Attachment doesn't exist, create it
			const int weaponAttachmentCount = weaponAttachmentNode->getChildCount();
			const char *boneName = "";
			Vec3 attachmentOffset(ZERO);
			Ang3 attachmentRotation(ZERO);

			for (int a = 0; a < weaponAttachmentCount; ++a)
			{
				const XmlNodeRef childNode = weaponAttachmentNode->getChild(a);

				if(childNode == (IXmlNode *)NULL)
				{
					continue;
				}

				if(!strcmp(childNode->getTag(), "Bone"))
				{
					childNode->getAttr("name", &boneName);
				}
				else if(!strcmp(childNode->getTag(), "Offset"))
				{
					childNode->getAttr("x", attachmentOffset.x);
					childNode->getAttr("y", attachmentOffset.y);
					childNode->getAttr("z", attachmentOffset.z);
				}
				else if(!strcmp(childNode->getTag(), "Rotation"))
				{
					float value = 0.0f;
					childNode->getAttr("x", value);
					attachmentRotation.x = DEG2RAD(value);
					childNode->getAttr("y", value);
					attachmentRotation.y = DEG2RAD(value);
					childNode->getAttr("z", value);
					attachmentRotation.z = DEG2RAD(value);
				}
			}

			const char *attachmentType = "";
			weaponAttachmentNode->getAttr("type", &attachmentType);

			if(!strcmp(attachmentType, ""))
			{
				CryWarning(VALIDATOR_MODULE_GAME, VALIDATOR_WARNING, "No Weapon Attachment type assigned! Skipping Weapon Attachment: %s", attachmentName);
				continue;
			}

			const bool isBoneAttachment = !strcmp(attachmentType, "Bone");
			const bool isFaceAttachment = !strcmp(attachmentType, "Face");

			//Bone attachment needs the bone name
			if (!strcmp(boneName, "") && isBoneAttachment)
			{
				CryWarning(VALIDATOR_MODULE_GAME, VALIDATOR_WARNING, "Bone Attachment with no bone name assigned! Skipping Weapon Attachment: %s", attachmentName);
				continue;
			}

			if(isBoneAttachment)
			{
				pAttachment = pAttachmentManager->CreateAttachment(attachmentName, CA_BONE, boneName);
			}
			else if(isFaceAttachment)
			{
				pAttachment = pAttachmentManager->CreateAttachment(attachmentName, CA_FACE, 0);
			}

			if(pAttachment)
			{
				if(isBoneAttachment)
				{
					m_boneAttachmentMap.insert(TBoneAttachmentMap::value_type(attachmentName, 0));
				}

				if(pAttachment && !attachmentOffset.IsZero())
				{
					QuatT attachmentQuat(IDENTITY);
					attachmentQuat.SetRotationXYZ(attachmentRotation, attachmentOffset);
					pAttachment->SetAttAbsoluteDefault( attachmentQuat );
					pAttachment->ProjectAttachment();
				}
			}
		}
	}
}
bool CGameTokenSystem::_InternalLoadLibrary( const char *filename, const char* tag )
{
	XmlNodeRef root = GetISystem()->LoadXmlFromFile( filename );
	if (!root)
	{
		GameWarning( _HELP("Unable to load game token database: %s"), filename );
		return false;
	}

	if (0 != strcmp( tag, root->getTag() ))
	{
		GameWarning( _HELP("Not a game tokens library : %s"), filename );
		return false;
	}

	// GameTokens are (currently) not saved with their full path
	// we expand it here to LibName.TokenName
	string libName;
	{
		const char *sLibName = root->getAttr("Name");
		if (sLibName == 0) {
			GameWarning( "GameTokensLibrary::LoadLibrary: Unable to find LibName in file '%s'", filename);
			return false;
		}
		libName = sLibName;
	}
 
	// we dont skip already loaded libraries anymore. We need to reload them to be sure that all necessary gametokens are present even if some level has not up-to-date libraries.
	if (!stl::find(m_libraries, libName)) //return true;
		m_libraries.push_back(libName);

	libName+= ".";

	int numChildren = root->getChildCount();
	for (int i=0; i<numChildren; i++)
	{
		XmlNodeRef node = root->getChild(i);

		const char *sName = node->getAttr("Name");
		const char *sType = node->getAttr("Type");
		const char *sValue = node->getAttr("Value");
		const char *sLocalOnly = node->getAttr("LocalOnly");
		int localOnly=atoi(sLocalOnly);

		EFlowDataTypes tokenType = eFDT_Any;
		if (0 == strcmp(sType,"Int"))
			tokenType = eFDT_Int;
		else if (0 == strcmp(sType,"Float"))
			tokenType = eFDT_Float;
		else if (0 == strcmp(sType,"EntityId"))
			tokenType = eFDT_EntityId;
		else if (0 == strcmp(sType,"Vec3"))
			tokenType = eFDT_Vec3;
		else if (0 == strcmp(sType,"String"))
			tokenType = eFDT_String;
		else if (0 == strcmp(sType,"Bool"))
			tokenType = eFDT_Bool;

		if (tokenType == eFDT_Any)
		{
			GameWarning(_HELP("Unknown game token type %s in token %s (%s:%d)"),sType,sName,node->getTag(),node->getLine());
			continue;
		}

		TFlowInputData initialValue = TFlowInputData(string(sValue));

		string fullName (libName);
		fullName+=sName;
		
		IGameToken *pToken = stl::find_in_map(*m_pGameTokensMap,fullName,NULL);
		if (!pToken)
		{
			pToken = SetOrCreateToken( fullName,initialValue );
			if (pToken && localOnly)
				pToken->SetFlags(pToken->GetFlags()|EGAME_TOKEN_LOCALONLY);
		}
	}
	return true;
}
예제 #18
0
void CHUDMissionObjectiveSystem::LoadObjectiveAnalysisData(const char* levelpath)
{
	CryFixedStringT<128> filename;
	if(levelpath==NULL)
	{
		filename = "Libs/UI/ObjectivesAnalysis.xml";
	}
	else
	{
		filename.Format("%s/leveldata/ObjectivesAnalysis.xml", levelpath);
	}

	XmlNodeRef root = GetISystem()->LoadXmlFromFile(filename.c_str());
	if (root == 0)
		return;

	XmlNodeRef analysisDataContainerNode = root->findChild("AnalysisData");		
	SObjectiveAnalysisData analysisData;
	SSingleObjectiveAnalysisData singleAnalysisData;
	if (analysisDataContainerNode != 0)
	{
		for(int i = 0; i < analysisDataContainerNode->getChildCount(); ++i)
		{
			XmlNodeRef analysisDataNode = analysisDataContainerNode->getChild(i);
			const char* szOuterId = analysisDataNode->getAttr("Id");
			if (szOuterId == NULL || szOuterId[0] == '\0')
			{
				GameWarning("CHUDMissionObjectiveSystem::LoadObjectiveAnalysisData: Failed to load analysisdata, invalid id");
				continue;
			}
			
			analysisData.m_singleObjectiveData.clear();
			const int iNumSingleAnalysis = analysisDataNode->getChildCount();
			bool bFailedAddedSingleAnalysis = false;
			for (int j = 0; j < iNumSingleAnalysis; j++)
			{
				XmlNodeRef singleAnalysisDataNode = analysisDataNode->getChild(j);

				const char* szSingleId;
				int iUseOuterId;
				// UseOuterId saves needing to duplicate text to the outer Id
				bool bResult = singleAnalysisDataNode->getAttr("UseOuterId", iUseOuterId);
				if (bResult && (iUseOuterId == 1))
				{
					szSingleId = szOuterId;
				}
				else
				{
					szSingleId = analysisDataNode->getAttr("Id");
				}

				if (szSingleId == NULL || szSingleId[0] == '\0')
				{
					GameWarning("CHUDMissionObjectiveSystem::LoadObjectiveAnalysisData: Failed to load single analysisdata section for analysis: %s, invalid id", szOuterId);
					bFailedAddedSingleAnalysis = true;
					break;
				}

				singleAnalysisData.m_id = szSingleId;
				singleAnalysisDataNode->getAttr("Percent", singleAnalysisData.m_fPercent);
				analysisData.m_singleObjectiveData.push_back(singleAnalysisData);
			}

			if (bFailedAddedSingleAnalysis || analysisData.m_singleObjectiveData.size() < 1)
			{
				GameWarning("CHUDMissionObjectiveSystem::LoadObjectiveAnalysisData: Failed to load analysisdata: %s, problem with section data", szOuterId);
				continue;
			}

			analysisDataNode->getAttr("OverrideSectionID",analysisData.m_iOverrideIndex);
			analysisDataNode->getAttr("AttachInWorld", analysisData.m_bAttachInWorld);
			m_objectiveAnalysisData[szOuterId] = analysisData;
		}
	}
}
예제 #19
0
//////////////////////////////////////////////////////////////////////////
// Set event targets from the XmlNode exported by Editor.
void CScriptProxy::SetEventTargets( XmlNodeRef &eventTargetsNode )
{
	std::set<string>                sourceEvents;
	std::vector<SEntityEventTarget> eventTargets;

	IScriptSystem* pSS = GetIScriptSystem();

	for (int i = 0; i < eventTargetsNode->getChildCount(); i++)
	{
		XmlNodeRef eventNode = eventTargetsNode->getChild(i);

		SEntityEventTarget et;
		et.event = eventNode->getAttr("Event");
		if (!eventNode->getAttr("Target", et.target))
			et.target = 0; // failed reading...
		et.sourceEvent = eventNode->getAttr("SourceEvent");

		if (et.event.empty() || !et.target || et.sourceEvent.empty())
			continue;

		eventTargets.push_back(et);
		sourceEvents.insert(et.sourceEvent);
	}
	if (eventTargets.empty())
		return;

	SmartScriptTable pEventsTable;

	if (!m_pThis->GetValue( "Events",pEventsTable ))
	{
		pEventsTable = pSS->CreateTable();
		// assign events table to the entity self script table.
		m_pThis->SetValue( "Events",pEventsTable );
	}

	for (std::set<string>::iterator it = sourceEvents.begin(); it != sourceEvents.end(); ++it)
	{
		SmartScriptTable pTrgEvents(pSS);

		string sourceEvent = *it;

		pEventsTable->SetValue( sourceEvent.c_str(),pTrgEvents );

		// Put target events to table.
		int trgEventIndex = 1;
		for (size_t i = 0; i < eventTargets.size(); i++)
		{
			SEntityEventTarget &et = eventTargets[i];
			if (et.sourceEvent == sourceEvent)
			{
				SmartScriptTable pTrgEvent(pSS);

				pTrgEvents->SetAt( trgEventIndex,pTrgEvent );
				trgEventIndex++;
				ScriptHandle hdl;
				hdl.n = et.target;
				pTrgEvent->SetAt( 1, hdl);
				pTrgEvent->SetAt( 2,et.event.c_str());
			}
		}
	}
}
예제 #20
0
void CBattleDust::ReloadXml()
{
	// first empty out the previous stuff
	m_weaponPower.clear();
	m_explosionPower.clear();
	m_vehicleExplosionPower.clear();
	m_bulletImpactPower.clear();

	IXmlParser*	pxml = g_pGame->GetIGameFramework()->GetISystem()->GetXmlUtils()->CreateXmlParser();
	if(!pxml)
		return;

	XmlNodeRef node = GetISystem()->LoadXmlFromFile(PathUtil::GetGameFolder() + "/Scripts/GameRules/BattleDust.xml");
	if(!node)
		return;

	XmlNodeRef paramsNode = node->findChild("params");
	if(paramsNode)
	{
		paramsNode->getAttr("fogspawnpower", m_entitySpawnPower);
		paramsNode->getAttr("defaultlifetime", m_defaultLifetime);
		paramsNode->getAttr("maxlifetime", m_maxLifetime);
		paramsNode->getAttr("maxeventpower", m_maxEventPower);
		paramsNode->getAttr("minparticlecount", m_minParticleCount);
		paramsNode->getAttr("maxparticlecount", m_maxParticleCount);
		paramsNode->getAttr("distancebetweenevents", m_distanceBetweenEvents);
	}

	XmlNodeRef eventsNode = node->findChild("events");
	if(eventsNode)
	{
		// corresponds to the eBDET_ShotFired event
		XmlNodeRef shotNode = eventsNode->findChild("shotfired");
		if(shotNode)
		{
			for (int i = 0; i < shotNode->getChildCount(); ++i)
			{
				XmlNodeRef weaponNode = shotNode->getChild(i);
				if(weaponNode)
				{
					XmlString name;
					float power = 1.0f;
					float lifetime = 1.0f;
					weaponNode->getAttr("name", name);
					weaponNode->getAttr("power", power);
					weaponNode->getAttr("lifetime", lifetime);

					if(!strcmp(name, "default"))
					{
						m_defaultWeapon.m_power = power;
						m_defaultWeapon.m_lifetime = lifetime;
					}
					else
					{
						SBattleEventParameter param;
						param.m_name = name;
						param.m_pClass = gEnv->pEntitySystem->GetClassRegistry()->FindClass(name);
						param.m_power = power;
						param.m_lifetime = lifetime;
						m_weaponPower.push_back(param);
					}
				}
			}
		}

		XmlNodeRef explodeNode = eventsNode->findChild("explosion");
		if(explodeNode)
		{
			for(int i=0; i < explodeNode->getChildCount(); ++i)
			{
				XmlNodeRef explosiveNode = explodeNode->getChild(i);
				if(explosiveNode)
				{
					XmlString name;
					float power = 1.0f;
					float lifetime = 1.0f;
					explosiveNode->getAttr("name", name);
					explosiveNode->getAttr("power", power);
					explosiveNode->getAttr("lifetime", lifetime);

					if(!strcmp(name, "default"))
					{
						m_defaultExplosion.m_power = power;
						m_defaultExplosion.m_lifetime = lifetime;
					}
					else
					{
						SBattleEventParameter param;
						param.m_name = name;
						param.m_pClass = gEnv->pEntitySystem->GetClassRegistry()->FindClass(name);
						param.m_power = power;
						param.m_lifetime = lifetime;
						m_explosionPower.push_back(param);
					}
				}
			}
		}

		XmlNodeRef vehicleExplodeNode = eventsNode->findChild("vehicleexplosion");
		if(vehicleExplodeNode)
		{
			for(int i=0; i < vehicleExplodeNode->getChildCount(); ++i)
			{
				XmlNodeRef vehicleNode = vehicleExplodeNode->getChild(i);
				if(vehicleNode)
				{
					XmlString name;
					float power = 1.0f;
					float lifetime = 1.0f;
					vehicleNode->getAttr("name", name);
					vehicleNode->getAttr("power", power);
					vehicleNode->getAttr("lifetime", lifetime);

					if(!strcmp(name, "default"))
					{
						m_defaultVehicleExplosion.m_power = power;
						m_defaultVehicleExplosion.m_lifetime = lifetime;
					}
					else
					{
						SBattleEventParameter param;
						param.m_name = name;
						param.m_pClass = gEnv->pEntitySystem->GetClassRegistry()->FindClass(name);
						param.m_power = power;
						param.m_lifetime = lifetime;
						m_vehicleExplosionPower.push_back(param);
					}
				}
			}
		}

		XmlNodeRef impactNode = eventsNode->findChild("bulletimpact");
		if(impactNode)
		{
			for(int i=0; i < impactNode->getChildCount(); ++i)
			{
				XmlNodeRef impact = impactNode->getChild(i);
				if(impact)
				{
					XmlString name;
					float power = 1.0f;
					float lifetime = 1.0f;
					impact->getAttr("name", name);
					impact->getAttr("power", power);
					impact->getAttr("lifetime", lifetime);

					if(!strcmp(name, "default"))
					{
						m_defaultBulletImpact.m_power = power;
						m_defaultBulletImpact.m_lifetime = lifetime;
					}
					else
					{
						SBattleEventParameter param;
						param.m_name = name;
						param.m_pClass = gEnv->pEntitySystem->GetClassRegistry()->FindClass(name);
						param.m_lifetime = lifetime;
						param.m_power = power;
						m_bulletImpactPower.push_back(param);
					}
				}
			}
		}
	}
}
//------------------------------------------------------------------------
void CGameRulesCommonDamageHandling::Init( XmlNodeRef xml )
{
	m_pGameRules = g_pGame->GetGameRules();

	// Reserved hit types - in sync with RESERVED_HIT_TYPES
	/*00*/ //m_pGameRules->RegisterHitType("invalid",							CGameRules::EHitTypeFlag::None);
	/*01*/ m_pGameRules->RegisterHitType("melee",								CGameRules::EHitTypeFlag::IsMeleeAttack | CGameRules::EHitTypeFlag::IgnoreHeadshots);
	/*02*/ m_pGameRules->RegisterHitType("collision",						CGameRules::EHitTypeFlag::Server);
	/*03*/ m_pGameRules->RegisterHitType("frag",								CGameRules::EHitTypeFlag::Server | CGameRules::EHitTypeFlag::AllowPostDeathDamage);
	/*04*/ m_pGameRules->RegisterHitType("explosion",						CGameRules::EHitTypeFlag::Server | CGameRules::EHitTypeFlag::AllowPostDeathDamage);
	/*05*/ m_pGameRules->RegisterHitType("stealthKill",					CGameRules::EHitTypeFlag::Server | CGameRules::EHitTypeFlag::AllowPostDeathDamage);
	/*06*/ m_pGameRules->RegisterHitType("silentMelee",					CGameRules::EHitTypeFlag::IsMeleeAttack | CGameRules::EHitTypeFlag::SinglePlayerOnly | CGameRules::EHitTypeFlag::IgnoreHeadshots);
	/*07*/ m_pGameRules->RegisterHitType("punish",							CGameRules::EHitTypeFlag::ClientSelfHarm);
	/*08*/ m_pGameRules->RegisterHitType("punishFall",					CGameRules::EHitTypeFlag::ClientSelfHarm);
	/*09*/ m_pGameRules->RegisterHitType("mike_burn",                     CGameRules::EHitTypeFlag::ValidationRequired);		
	/*10*/ m_pGameRules->RegisterHitType("fall",								CGameRules::EHitTypeFlag::ClientSelfHarm);
	/*11*/ m_pGameRules->RegisterHitType("normal",							CGameRules::EHitTypeFlag::Server);	//Used for killing players so they can switch teams
	/*12*/ m_pGameRules->RegisterHitType("fire",								CGameRules::EHitTypeFlag::Server); // used by PressurizedObject.lua
	/*13*/ m_pGameRules->RegisterHitType("bullet",							CGameRules::EHitTypeFlag::ValidationRequired);
	/*14*/ m_pGameRules->RegisterHitType("stamp",						CGameRules::EHitTypeFlag::Server | CGameRules::EHitTypeFlag::CustomValidationRequired);
	/*15*/ m_pGameRules->RegisterHitType("environmentalThrow",	CGameRules::EHitTypeFlag::CustomValidationRequired | CGameRules::EHitTypeFlag::AllowPostDeathDamage | CGameRules::EHitTypeFlag::IgnoreHeadshots);
	/*16*/ m_pGameRules->RegisterHitType("meleeLeft",						CGameRules::EHitTypeFlag::IsMeleeAttack | CGameRules::EHitTypeFlag::SinglePlayerOnly | CGameRules::EHitTypeFlag::IgnoreHeadshots);
	/*17*/ m_pGameRules->RegisterHitType("meleeRight",					CGameRules::EHitTypeFlag::IsMeleeAttack | CGameRules::EHitTypeFlag::SinglePlayerOnly | CGameRules::EHitTypeFlag::IgnoreHeadshots);
	/*18*/ m_pGameRules->RegisterHitType("meleeKick",						CGameRules::EHitTypeFlag::IsMeleeAttack | CGameRules::EHitTypeFlag::SinglePlayerOnly | CGameRules::EHitTypeFlag::IgnoreHeadshots);
	/*19*/ m_pGameRules->RegisterHitType("meleeUppercut",				CGameRules::EHitTypeFlag::IsMeleeAttack | CGameRules::EHitTypeFlag::SinglePlayerOnly | CGameRules::EHitTypeFlag::IgnoreHeadshots);
	/*20*/ m_pGameRules->RegisterHitType("vehicleDestruction",	CGameRules::EHitTypeFlag::Server | CGameRules::EHitTypeFlag::AllowPostDeathDamage);
	/*21*/ m_pGameRules->RegisterHitType("electricity",				CGameRules::EHitTypeFlag::SinglePlayerOnly);
	/*22*/ m_pGameRules->RegisterHitType("stealthKill_Maximum",		CGameRules::EHitTypeFlag::SinglePlayerOnly);
	/*23*/ m_pGameRules->RegisterHitType("eventDamage",					CGameRules::EHitTypeFlag::ClientSelfHarm);
	/*24*/ m_pGameRules->RegisterHitType("VTOLExplosion",				CGameRules::EHitTypeFlag::Server);
	/*25*/ m_pGameRules->RegisterHitType("environmentalMelee",	CGameRules::EHitTypeFlag::IsMeleeAttack | CGameRules::EHitTypeFlag::CustomValidationRequired | CGameRules::EHitTypeFlag::AllowPostDeathDamage | CGameRules::EHitTypeFlag::IgnoreHeadshots);
	
	CRY_ASSERT(m_pGameRules->GetHitTypesCount() == CGameRules::EHitType::Unreserved);

	// Read any non-native hit_types from the HitTypes.xml file!
	XmlNodeRef xmlNode = gEnv->pSystem->LoadXmlFromFile( "Scripts/Entities/Items/HitTypes.xml" );

	if( xmlNode )
	{
		const int numEntries = xmlNode->getChildCount();
		for (int i = 0; i < numEntries; ++i)
		{
			XmlNodeRef hitTypeXML = xmlNode->getChild(i);

			if (strcmp(hitTypeXML->getTag(), "hit_type") != 0)
				continue;

			if( const char* pHitType = hitTypeXML->getAttr("name") )
			{
				TBitfield flags = CGameRules::EHitTypeFlag::None;

				if( const char * pHitTypeFlags = hitTypeXML->getAttr("flags"))
				{
					flags = AutoEnum_GetBitfieldFromString(pHitTypeFlags, CGameRules::s_hitTypeFlags, CGameRules::EHitTypeFlag::HIT_TYPES_FLAGS_numBits);
				}

				m_pGameRules->RegisterHitType( pHitType, flags );
			}
		}
	}
	m_scriptHitInfo.Create(gEnv->pScriptSystem);
}
예제 #22
0
bool CommunicationVoiceLibrary::LoadFromFile(const char* fileName)
{
	MEMSTAT_CONTEXT(EMemStatContextTypes::MSC_Other, 0, "Communication Voice Library" );
	MEMSTAT_CONTEXT_FMT(EMemStatContextTypes::MSC_Other, 0, "Voice Lib: %s",fileName );

	XmlNodeRef root = GetISystem()->LoadXmlFromFile(fileName);
	if (!root)
		return false;

	XmlNodeRef nodeWorksheet = root->findChild("Worksheet");
	if (!nodeWorksheet)
		return false;

	XmlNodeRef nodeTable = nodeWorksheet->findChild("Table");
	if (!nodeTable)
		return false;

	stack_string libName(PathUtil::GetFileName(fileName));

	VoiceLibraryID libraryID = GetVoiceLibraryID(libName.c_str());

	std::pair<VoiceLibraries::iterator, bool> iresult = m_libraries.insert(
		VoiceLibraries::value_type(libraryID, VoiceLibrary()));

	if (!iresult.second)
	{
		if (iresult.first->second.name == libName.c_str())
		{
			AIWarningID("<AICommunicationVoiceLibrary::LoadFromFile> ", 
				"Duplicate voice library '%s'!", libName.c_str());

			return false;
		}
		else
		{
			AIWarningID("<AICommunicationVoiceLibrary::LoadFromFile> ", 
				"Hash collision for voice library name '%s' and '%s'!", libName.c_str(), iresult.first->second.name.c_str());

			return false;
		}
	}

	VoiceLibrary& library = iresult.first->second;
	library.name = string(libName);
	
	VoiceGroup* voiceGroup = 0;
		
	string signalName;
	string lastSignalName;
	string voiceName;

	for (int rowCntr = 0, childN = 0; childN < nodeTable->getChildCount(); ++childN)
	{
		XmlNodeRef nodeRow = nodeTable->getChild(childN);
		if (!nodeRow->isTag("Row"))
			continue;

		++rowCntr;
		if (rowCntr == 1) // skip language
			continue;

		if (rowCntr == 2) // path
		{
			int cellN = 0;
			for (int childrenCntr = 0; childrenCntr < nodeRow->getChildCount(); ++childrenCntr)
			{
				XmlNodeRef nodeCell = nodeRow->getChild(childrenCntr);
				if (!nodeCell->isTag("Cell"))
					continue;

				++cellN;
				if (cellN == 2)
				{
					XmlNodeRef nodeCellData = nodeCell->findChild("Data");
					if (!nodeCellData)
						break;

					library.base = PathUtil::GetLocalizationFolder() + nodeCellData->getContent();
					if (!library.base.empty())
					{
						library.base.replace("\\", "/");
						if (library.base[library.base.length()-1] != '/')
							library.base.append("/");
					}
					break;
				}
			}
			continue;
		}

		if (rowCntr == 3) // headers
			continue;

		signalName.clear();
		voiceName.clear();
		
		for (int childrenCntr = 0, cellIndex = 1; childrenCntr < nodeRow->getChildCount(); ++childrenCntr, ++cellIndex)
		{
			XmlNodeRef nodeCell = nodeRow->getChild(childrenCntr);
			if (!nodeCell->isTag("Cell"))
				continue;

			if (nodeCell->haveAttr("ss:Index"))
			{
				const char* strIdx = nodeCell->getAttr("ss:Index");
				if (sscanf(strIdx, "%d", &cellIndex) != 1)
					continue;
			}

			XmlNodeRef nodeCellData = nodeCell->findChild("Data");
			if (!nodeCellData)
				continue;

			switch (cellIndex)
			{
			case 1:
				signalName = nodeCellData->getContent();
				break;
			case 2:
				voiceName = nodeCellData->getContent();
				break;
			}
		}

		if (!signalName.empty())
		{
			signalName.MakeLower();
			std::pair<VoiceGroups::iterator, bool> itresult = library.voiceGroups.insert(
				VoiceGroups::value_type(signalName, VoiceGroup()));

			voiceGroup = &itresult.first->second;
			// The 20 here comes from inspection of the resulting contents in memreplay
			voiceGroup->variations.reserve(20);

			if (!itresult.second)
			{
				if (lastSignalName != signalName)
					AIWarningID("<AICommunicationVoiceLibrary::LoadFromFile> ", 
						"Duplicate voice signal '%s' in file '%s'.", signalName.c_str(), libName.c_str());
			}

			lastSignalName = signalName;
		}

		if (!voiceGroup || voiceName.empty())
			continue;

		if ((library.base.find_first_of(':') == string::npos) && (voiceName.find_first_of(':') == string::npos))
			voiceName.append(".wav");

		if (voiceGroup->variations.size() < MaxVariationCount)
			voiceGroup->variations.push_back(voiceName);
		else
			AIWarningID("<AICommunicationVoiceLibrary::LoadFromFile> ", 
			"Too many voice variations for signal '%s' in file '%s'. Limit is 32.", signalName.c_str(), libName.c_str());
	}

	return true;
}
void CEquipmentSystemInterface::InitItems(IGameToEditorInterface* pGTE)
{
	// Get ItemParams from ItemSystem
	// Creates the following entries
	// "item"               All Item classes
	// "item_selectable"    All Item classes which can be selected
	// "item_givable",      All Item classes which can be given
	// "weapon"             All Weapon classes (an Item of class 'Weapon' or an Item which has ammo)
	// "weapon_selectable"  All Weapon classes which can be selected
	// "weapon_givable"     All Weapon classes which can be given
	// and for any weapon which has ammo
	// "ammo_WEAPONNAME"    All Ammos for this weapon

	IItemSystem* pItemSys = m_pIItemSystem;
	int maxCountItems = pItemSys->GetItemParamsCount();
	int maxAllocItems = maxCountItems+1; // allocate one more to store empty
	const char** allItemClasses = new const char*[maxAllocItems];
	const char** givableItemClasses = new const char*[maxAllocItems];
	const char** selectableItemClasses = new const char*[maxAllocItems];
	const char** allWeaponClasses = new const char*[maxAllocItems];
	const char** givableWeaponClasses = new const char*[maxAllocItems];
	const char** selectableWeaponClasses = new const char*[maxAllocItems];

	int numAllItems = 0;
	int numAllWeapons = 0;
	int numGivableItems = 0;
	int numSelectableItems = 0;
	int numSelectableWeapons = 0;
	int numGivableWeapons = 0;
	std::set<string> allAmmosSet;

	// store default "---" -> "" value
	{
		const char* empty = "";
		selectableWeaponClasses[numSelectableWeapons++] = empty;
		givableWeaponClasses[numGivableWeapons++] = empty;
		allWeaponClasses[numAllWeapons++] = empty;
		selectableItemClasses[numSelectableItems++] = empty;
		givableItemClasses[numGivableItems++] = empty;
		allItemClasses[numAllItems++] = empty;
		allAmmosSet.insert(empty);
	}

	for (int i=0; i<maxCountItems; ++i)
	{
		const char* itemName = pItemSys->GetItemParamName(i);
		allItemClasses[numAllItems++] = itemName;

		const char* itemDescriptionFile = pItemSys->GetItemParamsDescriptionFile(itemName);
		
		CRY_ASSERT(itemDescriptionFile);
		XmlNodeRef itemRootParams = gEnv->pSystem->LoadXmlFromFile(itemDescriptionFile);

		if (!itemRootParams)
		{
			GameWarning("Item description file %s doesn't exist for item %s", itemDescriptionFile, itemName);
			continue;
		}

		CGameXmlParamReader rootReader(itemRootParams);
		const char* inheritItem = itemRootParams->getAttr("inherit");
		bool isInherited = (inheritItem && inheritItem[0] != 0);
		if (isInherited)
		{
			const char* baseItemFile = pItemSys->GetItemParamsDescriptionFile(inheritItem);
			itemRootParams = gEnv->pSystem->LoadXmlFromFile(baseItemFile);
		}

		if (itemRootParams)
		{
			bool givable = false;
			bool selectable = false;
			bool uiWeapon = false;
			XmlNodeRef childItemParams = itemRootParams->findChild("params");
			if (childItemParams) 
			{
				CGameXmlParamReader reader(childItemParams);

				//the equipeable flag is supposed to be used for weapons that are not givable
				//but that are still needed to be in the equipment weapon list.
				bool equipeable = false;
				reader.ReadParamValue<bool>("equipeable", equipeable);
				reader.ReadParamValue<bool>("giveable", givable);
				givable |= equipeable;

				reader.ReadParamValue<bool>("selectable", selectable);
				reader.ReadParamValue<bool>("ui_weapon", uiWeapon);
			}

			if (givable)
				givableItemClasses[numGivableItems++] = itemName;
			if (selectable)
				selectableItemClasses[numSelectableItems++] = itemName;

			XmlNodeRef childAccessoriesNode = itemRootParams->findChild("accessories");

			if(childAccessoriesNode)
			{
				const int numAccessories = childAccessoriesNode->getChildCount();

				for(int childIdx = 0; childIdx < numAccessories; childIdx++)
				{
					XmlNodeRef childAccessory = childAccessoriesNode->getChild(childIdx);

					if(childAccessory && stricmp(childAccessory->getTag(), "accessory") == 0)
					{
						const char* accessoryName = childAccessory->getAttr("name");
						const char* categoryName = childAccessory->getAttr("category");			

						if(categoryName && accessoryName)
						{
							m_accessoryMap[itemName][categoryName].push_back(accessoryName);
						}
					}
				}
			}

			XmlNodeRef ammosNode = itemRootParams->findChild("ammos");
			if (ammosNode)
			{
				CGameXmlParamReader reader(ammosNode);

				const int maxAmmos = reader.GetUnfilteredChildCount();
				int numAmmos = 0;
				const char** ammoNames = new const char*[maxAmmos];
				for (int j=0; j<maxAmmos; ++j)
				{
					XmlNodeRef ammoChildNode = reader.GetFilteredChildAt(j);
					if ((ammoChildNode != NULL) && stricmp(ammoChildNode->getTag(), "ammo") == 0)
					{
						const char* ammoName = ammoChildNode->getAttr("name");
						if (ammoName && ammoName[0])
						{
							ammoNames[numAmmos] = ammoName;
							++numAmmos;
							allAmmosSet.insert(ammoName);
						}
					}
				}
				if (numAmmos > 0)
				{
					// make it a weapon when there's ammo
					allWeaponClasses[numAllWeapons++] = itemName;
					if (selectable)
						selectableWeaponClasses[numSelectableWeapons++] = itemName;
					if (givable)
						givableWeaponClasses[numGivableWeapons++] = itemName;

					string ammoEntryName = "ammo_";
					ammoEntryName+=itemName;
					pGTE->SetUIEnums(ammoEntryName.c_str(), ammoNames, numAmmos);
				}
				delete[] ammoNames;
			}
			else
			{
				const char* itemClass = itemRootParams->getAttr("class");
				if (uiWeapon || (itemClass != 0 && stricmp(itemClass, "weapon") == 0))
				{
					// make it a weapon when there's ammo
					allWeaponClasses[numAllWeapons++] = itemName;
					if (selectable)
						selectableWeaponClasses[numSelectableWeapons++] = itemName;
					if (givable)
						givableWeaponClasses[numGivableWeapons++] = itemName;
				}
			}
		}
	}

	int numAllAmmos = 0;
	const char** allAmmos = new const char*[allAmmosSet.size()];
	std::set<string>::const_iterator iter (allAmmosSet.begin());
	while (iter != allAmmosSet.end())
	{
		allAmmos[numAllAmmos++] = iter->c_str();
		++iter;
	}
	pGTE->SetUIEnums("ammos", allAmmos, numAllAmmos);
	ToContainer(allAmmos+1, numAllAmmos-1, m_itemMap["Ammo"]);
	delete[] allAmmos;

	pGTE->SetUIEnums("weapon_selectable", selectableWeaponClasses, numSelectableWeapons);
	pGTE->SetUIEnums("weapon_givable", givableWeaponClasses, numGivableWeapons);
	pGTE->SetUIEnums("weapon", allWeaponClasses, numAllWeapons);
	pGTE->SetUIEnums("item_selectable", selectableItemClasses, numSelectableItems);
	pGTE->SetUIEnums("item_givable", givableItemClasses, numGivableItems);
	pGTE->SetUIEnums("item", allItemClasses, numAllItems);

	ToContainer(allItemClasses+1,numAllItems-1,m_itemMap["Item"]);
	ToContainer(givableItemClasses+1,numGivableItems-1,m_itemMap["ItemGivable"]);
	ToContainer(allWeaponClasses+1,numAllWeapons-1,m_itemMap["Weapon"]);

	delete[] selectableWeaponClasses;
	delete[] givableWeaponClasses;
	delete[] allWeaponClasses;
	delete[] selectableItemClasses;
	delete[] givableItemClasses; 
	delete[] allItemClasses;
}