//
// This method starts the parser that will either load one file
//	or many based on pszFilePath.
// Input: pszFilePath - FS path to KeyValue file(s) for parsing.
//						extentions are defined using .X
//
void CScriptParser::InitParser( const char *pszPath, bool bAllowNonEncryptedSearch /*=true*/, bool bAllowEncryptedSearch /*=true*/ )
{
	// If you hit this assert, check to see where your instancing 
	// CScriptParser, make sure it isn't before the filesystem inits
	Assert( filesystem );
	Assert( pszPath );

	// Have we already been parsed?
	// TODO: Maybe just issue a DevWarning here instead of bailing
	if( m_bParsed )
		return;

	// Copy the file path to tweak the extensions and fix it up
	char szFilePath[FILE_PATH_MAX_LENGTH];
	V_FixupPathName( szFilePath, FILE_PATH_MAX_LENGTH, pszPath );

	//Search for unencrypted files
	if( bAllowNonEncryptedSearch )
	{
		Q_SetExtension( szFilePath, GetNonEncryptedEXT(), FILE_PATH_MAX_LENGTH );
		SearchForFiles( szFilePath );
	}

	//Search for encrypted files
	if( bAllowEncryptedSearch )
	{
		Q_SetExtension( szFilePath, GetEncryptedEXT(), FILE_PATH_MAX_LENGTH );
		SearchForFiles( szFilePath );
	}

	m_bParsed = true;
}
Пример #2
0
CChoreoScene *C_SceneEntity::LoadScene( const char *filename )
{
	char loadfile[ 512 ];
	Q_strncpy( loadfile, filename, sizeof( loadfile ) );
	Q_SetExtension( loadfile, ".vcd", sizeof( loadfile ) );
	Q_FixSlashes( loadfile );

	char *buffer = NULL;
	size_t bufsize = scenefilecache->GetSceneBufferSize( loadfile );
	if ( bufsize <= 0 )
		return NULL;

	buffer = new char[ bufsize ];
	if ( !scenefilecache->GetSceneData( filename, (byte *)buffer, bufsize ) )
	{
		delete[] buffer;
		return NULL;
	}

	g_TokenProcessor.SetBuffer( buffer );
	CChoreoScene *scene = ChoreoLoadScene( loadfile, this, &g_TokenProcessor, Scene_Printf );

	delete[] buffer;
	return scene;
}
Пример #3
0
//-----------------------------------------------------------------------------
// The application object
//-----------------------------------------------------------------------------
void CSFMGenApp::GenerateSFMFiles( SFMGenInfo_t& info )
{
	char pRelativeModelPath[MAX_PATH];
	Q_ComposeFileName( "models", info.m_pModelName, pRelativeModelPath, sizeof(pRelativeModelPath) );
	Q_SetExtension( pRelativeModelPath, ".mdl", sizeof(pRelativeModelPath) );
	MDLHandle_t hMDL = g_pMDLCache->FindMDL( pRelativeModelPath );
	if ( hMDL == MDLHANDLE_INVALID )
	{
		Warning( "sfmgen: Model %s doesn't exist!\n", pRelativeModelPath );
		return;
	}

	studiohdr_t *pStudioHdr = g_pMDLCache->GetStudioHdr( hMDL );
	if ( !pStudioHdr || g_pMDLCache->IsErrorModel( hMDL ) )
	{
		Warning( "sfmgen: Model %s doesn't exist!\n", pRelativeModelPath );
		return;
	}

	CUtlBuffer buf( 0, 0, CUtlBuffer::TEXT_BUFFER );
	if ( !g_pFullFileSystem->ReadFile( info.m_pCSVFile, NULL, buf ) )
	{
		Warning( "sfmgen: Unable to load file %s\n", info.m_pCSVFile );
		return;
	}

	CUtlVector< SFMInfo_t > infoList;
	ParseCSVFile( buf, infoList, 1 );

	int nCount = infoList.Count();
	if ( nCount == 0 )
	{
		Warning( "sfmgen: no files to create!\n" );
		return;
	}

	UniqueifyNames( infoList );

	// Construct full path to the output directories
	char pFullPath[MAX_PATH];
	char pFullFacPathBuf[MAX_PATH];
	const char *pExportFacPath = NULL;
	ComputeFullPath( info.m_pOutputDirectory, pFullPath, sizeof(pFullPath) );
	if ( info.m_pExportFacDirectory )
	{
		ComputeFullPath( info.m_pExportFacDirectory, pFullFacPathBuf, sizeof(pFullFacPathBuf) );
		pExportFacPath = pFullFacPathBuf;
	}

	for ( int i = 0; i < nCount; ++i )
	{
		GenerateSFMFile( info, infoList[i], pStudioHdr, pFullPath, pExportFacPath ); 
	}
}
void CASW_Mission_Chooser_Source_Local::OnSaveDeleted(const char *szSaveName)
{
	char fixedname[ 256 ];
	Q_strncpy( fixedname, szSaveName, sizeof( fixedname ) );
	Q_SetExtension( fixedname, ".campaignsave", sizeof( fixedname ) );
	// check if this save is in the list of summaries, if so, remove it
	for (int i=0;i<m_SavedCampaignList.Count();i++)
	{
		if (!Q_stricmp(m_SavedCampaignList[i].m_szSaveName, fixedname))
		{
			m_SavedCampaignList.Remove(i);
			return;
		}
	}
}
Пример #5
0
bool HasMultipleBones( const char *pFilename )
{
	char outName[1024];
	studiohdr_t hdr;
	Q_strncpy( outName, pFilename, sizeof(outName) );
	Q_SetExtension( outName, ".mdl", sizeof(outName) );
	FileHandle_t fp = g_pFileSystem->Open( outName, "rb", TOOLS_READ_PATH_ID );
	if ( fp == FILESYSTEM_INVALID_HANDLE )
		return false;

	g_pFileSystem->Read( &hdr, sizeof(hdr), fp );
	g_pFileSystem->Close( fp );
	if ( hdr.numbones > 1 )
		return true;
	return false;
}
Пример #6
0
// schedules a map to be compiled
void CASW_Map_Builder::ScheduleMapBuild(const char* pszMap, const float fTime)
{
	if ( m_iBuildStage != STAGE_NONE )
	{
		Log_Warning( LOG_TilegenGeneral, "Map builder is currently busy, ignoring request to schedule map build for map '%s'", pszMap );
		return;
	}

	Q_strncpy( m_szLayoutName, Q_UnqualifiedFileName( pszMap ), _countof( m_szLayoutName ) );
	Q_SetExtension( m_szLayoutName, "layout", _countof( m_szLayoutName ) );
	m_flStartProcessingTime = fTime;
	m_bStartedGeneration = false;
	m_iBuildStage = STAGE_MAP_BUILD_SCHEDULED;
	m_flProgress = 0.0f;

	Q_snprintf( m_szStatusMessage, sizeof( m_szStatusMessage ), "Generating map..." );
}
Пример #7
0
CChoreoScene *C_SceneEntity::LoadScene( const char *filename )
{
	char loadfile[ 512 ];
	Q_strncpy( loadfile, filename, sizeof( loadfile ) );
	Q_SetExtension( loadfile, ".vcd", sizeof( loadfile ) );
	Q_FixSlashes( loadfile );

	char *pBuffer = NULL;
	size_t bufsize = scenefilecache->GetSceneBufferSize( loadfile );
	if ( bufsize <= 0 )
		return NULL;

	pBuffer = new char[ bufsize ];
	if ( !scenefilecache->GetSceneData( filename, (byte *)pBuffer, bufsize ) )
	{
		delete[] pBuffer;
		return NULL;
	}

	CChoreoScene *pScene;
	if ( IsBufferBinaryVCD( pBuffer, bufsize ) )
	{
		pScene = new CChoreoScene( this );
		CUtlBuffer buf( pBuffer, bufsize, CUtlBuffer::READ_ONLY );
		if ( !pScene->RestoreFromBinaryBuffer( buf, loadfile, &g_ChoreoStringPool ) )
		{
			Warning( "Unable to restore binary scene '%s'\n", loadfile );
			delete pScene;
			pScene = NULL;
		}
		else
		{
			pScene->SetPrintFunc( Scene_Printf );
			pScene->SetEventCallbackInterface( this );
		}
	}
	else
	{
		g_TokenProcessor.SetBuffer( pBuffer );
		pScene = ChoreoLoadScene( loadfile, this, &g_TokenProcessor, Scene_Printf );
	}

	delete[] pBuffer;
	return pScene;
}
Пример #8
0
bool LoadStudioCollisionModel( char const* pModelName, CUtlBuffer& buf )
{
	char tmp[1024];
	Q_strncpy( tmp, pModelName, sizeof( tmp ) );
	Q_SetExtension( tmp, ".phy", sizeof( tmp ) );
	// No luck, gotta build it	
	if (!LoadFile( tmp, buf ))
	{
		// this is not an error, the model simply has no PHY file
		return false;
	}

	phyheader_t *header = (phyheader_t *)buf.PeekGet();

	if ( header->size != sizeof(*header) || header->solidCount <= 0 )
		return false;

	return true;
}
Пример #9
0
// schedules a map to be randomly generated
void CASW_Map_Builder::ScheduleMapGeneration( const char* pszMap, const float fTime, KeyValues *pMissionSettings, KeyValues *pMissionDefinition )
{
	if ( m_iBuildStage != STAGE_NONE )
	{
		Log_Warning( LOG_TilegenGeneral, "Map builder is currently busy, ignoring request to schedule map generation for map '%s'", pszMap );
		return;
	}

	Q_strncpy( m_szLayoutName, Q_UnqualifiedFileName( pszMap ), _countof( m_szLayoutName ) );
	Q_SetExtension( m_szLayoutName, "layout", _countof( m_szLayoutName ) );
	m_pMissionSettings = pMissionSettings;
	m_pMissionDefinition = pMissionDefinition;
	m_flStartProcessingTime = fTime;
	m_iBuildStage = STAGE_GENERATE;
	m_bStartedGeneration = false;
	m_nLevelGenerationRetryCount = 0;
	m_flProgress = 0.0f;

	Q_snprintf( m_szStatusMessage, sizeof( m_szStatusMessage ), "Generating map..." );
}
Пример #10
0
//-----------------------------------------------------------------------------
// Purpose: 
//-----------------------------------------------------------------------------
void CEnvBeam::Precache( void )
{
	if ( !Q_stristr( STRING(m_iszSpriteName), ".vmt" ) )
	{
		// HACK/YWB:  This was almost always the laserbeam.spr, so alloc'ing the name a second time with the proper extension isn't going to
		//  kill us on memrory.
		//Warning( "Level Design Error:  %s (%i:%s) Sprite name (%s) missing .vmt extension!\n",
		//	STRING( m_iClassname ), entindex(), GetEntityName(), STRING(m_iszSpriteName) );

		char fixedname[ 512 ];
		Q_strncpy( fixedname, STRING( m_iszSpriteName ), sizeof( fixedname ) );

		Q_SetExtension( fixedname, ".vmt", sizeof( fixedname ) );
		
		m_iszSpriteName = AllocPooledString( fixedname );
	}

	g_iszPhysicsPropClassname = AllocPooledString( "prop_physics" );

	m_spriteTexture = PrecacheModel( STRING(m_iszSpriteName) );
	BaseClass::Precache();
}
Пример #11
0
//-----------------------------------------------------------------------------
// Creates a single sfm file
//-----------------------------------------------------------------------------
void CSFMGenApp::GenerateSFMFile( const SFMGenInfo_t& sfmGenInfo, const SFMInfo_t &info, 
	studiohdr_t *pStudioHdr, const char *pOutputDirectory, const char *pExportFacPath )
{
	CSFMSession session;
	session.Init();

	char pAnimationSetName[256];
	Q_FileBase( pStudioHdr->name, pAnimationSetName, sizeof(pAnimationSetName) );

	// Set the file id(	necessary for phoneme extraction)
	DmFileId_t fileid = g_pDataModel->FindOrCreateFileId( pAnimationSetName );
	session.Root()->SetFileId( fileid, TD_DEEP );
	g_pModelPresetGroupMgr->AssociatePresetsWithFile( fileid );

	// Get the shot.
	CDmeFilmClip *pMovie = session.Root()->GetValueElement<CDmeFilmClip>( "activeClip" );
	CDmeFilmClip* pShot = CastElement< CDmeFilmClip >( pMovie->GetFilmTrack()->GetClip( 0 ) );

	// Create a camera for the shot
	DmeCameraParams_t cameraParams( pAnimationSetName, vec3_origin, QAngle( 0, 180, 0 ) );
	cameraParams.origin.x = pStudioHdr->hull_max.x + 20;
	cameraParams.origin.z = Lerp( 0.95f, pStudioHdr->hull_min.z, pStudioHdr->hull_max.z );
	cameraParams.fov = 75.0f;
	CDmeCamera* pCamera = session.CreateCamera( cameraParams );
	pShot->SetCamera( pCamera );

	// Create a game model for the studio hdr
	CDmeGameModel *pGameModel = session.CreateEditorGameModel( pStudioHdr, vec3_origin, Quaternion( 0, 0, 0, 1 ) );

	// Create a scene for the shot
	CDmeDag *pScene = session.FindOrCreateScene( pShot, pAnimationSetName );
	pScene->AddChild( pGameModel );

	// Create a sound clip
	CDmeGameSound *pGameSound;
	CDmeSoundClip *pSoundClip = CreateSoundClip( pMovie, pAnimationSetName, info.m_GameSound, pStudioHdr, &pGameSound );

	pShot->SetDuration( pSoundClip->GetDuration() );
	pMovie->SetDuration( pSoundClip->GetDuration() );

	// Create an animation set
	CDmeAnimationSet *pAnimationSet = CreateAnimationSet( pMovie, pShot, pGameModel, pAnimationSetName, 0, false );

	// Extract phonemes
	if ( pSoundClip )
	{
		CExtractInfo extractInfo;
		extractInfo.m_pClip = pSoundClip;
		extractInfo.m_pSound = pGameSound;
		extractInfo.m_sHintText = info.m_Text;
		extractInfo.m_bUseSentence = sfmGenInfo.m_bUsePhonemesInWavs;

		ExtractDesc_t extractDesc;
		extractDesc.m_nExtractType = EXTRACT_WIPE_CLIP;
		extractDesc.m_pMovie = pMovie;
		extractDesc.m_pShot = pShot;
		extractDesc.m_pSet = pAnimationSet;
		extractDesc.m_flSampleRateHz = sfmGenInfo.m_flSampleRateHz;
		extractDesc.m_flSampleFilterSize = sfmGenInfo.m_flSampleFilterSize;
		extractDesc.m_WorkList.AddToTail( extractInfo );
		BuildFacialControlList( pShot, pAnimationSet, extractDesc.m_ControlList );
		sfm_phonemeextractor->Extract( SPEECH_API_LIPSINC, extractDesc, sfmGenInfo.m_bWritePhonemesInWavs );

		CExtractInfo &results = extractDesc.m_WorkList[ 0 ];
		CDmElement *pExtractionSettings = pGameSound->FindOrAddPhonemeExtractionSettings();
		pExtractionSettings->SetValue< float >( "duration", results.m_flDuration );
		// Store off phonemes
		if ( !pExtractionSettings->HasAttribute( "results" ) )
		{
			pExtractionSettings->AddAttribute( "results", AT_ELEMENT_ARRAY );
		}

		CDmrElementArray< CDmElement > resultsArray( pExtractionSettings, "results" );
		resultsArray.RemoveAll();
		for ( int i = 0; i < results.m_ApplyTags.Count(); ++i )
		{
			CBasePhonemeTag *tag = results.m_ApplyTags[ i ];
			CDmElement *tagElement = CreateElement< CDmElement >( ConvertPhoneme( tag->GetPhonemeCode() ), pGameSound->GetFileId() );
			tagElement->SetValue< float >( "start", tag->GetStartTime() );
			tagElement->SetValue< float >( "end", tag->GetEndTime() );
			resultsArray.AddToTail( tagElement );
		}

		if ( pExportFacPath )
		{
			char pFACFileName[MAX_PATH];
			Q_ComposeFileName( pExportFacPath, info.m_DMXFileName, pFACFileName, sizeof(pFACFileName) );
			Q_SetExtension( pFACFileName, ".dmx", sizeof(pFACFileName) ); 
			ExportFacialAnimation( pFACFileName, pMovie, pShot, pAnimationSet );
		}
	}

	SaveSFMFile( session.Root(), pOutputDirectory, info.m_DMXFileName );

	session.Shutdown();
}
Пример #12
0
// saves current save data to a keyvalues file
bool CASW_Campaign_Save::SaveGameToFile(const char *szFileName)
{
	// make sure the path and extension are correct
	char szFullFileName[256];
	char tempbuffer[256];
	if (szFileName==NULL)
	{
		if (m_CurrentSaveFileName == NULL_STRING)
		{
			Msg("Error: Couldn't save game to file as we have no name already and you didn't supply one.\n");
			return false;
		}
		Q_snprintf(szFullFileName, sizeof(szFullFileName), "%s", STRING(m_CurrentSaveFileName));
	}
	else
	{
		Q_snprintf(tempbuffer, sizeof(tempbuffer), "%s", szFileName);	
		Q_SetExtension( tempbuffer, ".campaignsave", sizeof(tempbuffer) );
		const char *pszNoPathName = Q_UnqualifiedFileName(tempbuffer);	
		Q_snprintf(szFullFileName, sizeof(szFullFileName), "save/%s", pszNoPathName);
	}

	// before saving, check if this is actually a completed campaign
	if (ASWGameRules())
	{
		int iLeft = ASWGameRules()->CampaignMissionsLeft();
		if (iLeft <= 0)
		{
			Msg("Deleting completed campaign %s", szFullFileName);
			filesystem->RemoveFile( szFullFileName, "GAME" );
			
			// notify the local mission source that a save has been deleted
			if (missionchooser && missionchooser->LocalMissionSource())
			{
				const char *pszNoPathName = Q_UnqualifiedFileName(szFullFileName);
				missionchooser->LocalMissionSource()->NotifySaveDeleted(pszNoPathName);
			}
			return true;
		}
	}
	//  we don't want completed campaigns lingering on disk

	KeyValues *pSaveKeyValues = new KeyValues( "CAMPAIGNSAVE" );
	
	pSaveKeyValues->SetInt("Version", m_iVersion);
	pSaveKeyValues->SetInt("SkillLevel", m_iLowestSkillLevelPlayed);
	pSaveKeyValues->SetString("CampaignName", m_CampaignName.Get());
	pSaveKeyValues->SetInt("CurrentPosition", m_iCurrentPosition);
	pSaveKeyValues->SetInt("NumMissionsComplete", m_iNumMissionsComplete);
	pSaveKeyValues->SetInt("InitialNumMissionsComplete", m_iInitialNumMissionsComplete);
	pSaveKeyValues->SetInt("Multiplayer", m_bMultiplayerGame ? 1 : 0);
	pSaveKeyValues->SetInt( "NumDeaths", m_iNumDeaths );
	pSaveKeyValues->SetBool( "FixedSkillPoints", m_bFixedSkillPoints );

	// update date
	int year, month, dayOfWeek, day, hour, minute, second;
	missionchooser->GetCurrentTimeAndDate(&year, &month, &dayOfWeek, &day, &hour, &minute, &second);
	//year = month = dayOfWeek = day = hour = minute = second = 0;
	Q_snprintf(m_DateTime.GetForModify(), 255, "%02d/%02d/%d %02d:%02d", month, day, year, hour, minute);
	pSaveKeyValues->SetString("DateTime", m_DateTime.Get());
	
	// write out each mission's status
	KeyValues *pSubSection;
	for (int i=0; i<ASW_MAX_MISSIONS_PER_CAMPAIGN; i++)
	{
		pSubSection = new KeyValues("MISSION");
		pSubSection->SetInt("MissionID", i);
		pSubSection->SetInt("MissionComplete", m_MissionComplete[i]);
		pSubSection->SetInt("NumRetries", m_NumRetries[i]);
		pSaveKeyValues->AddSubKey(pSubSection);
	}

	// write out each marine's stats
	for (int MarineID=0; MarineID<ASW_NUM_MARINE_PROFILES; MarineID++)
	{
		pSubSection = new KeyValues("MARINE");
		pSubSection->SetInt("MarineID", MarineID);

		pSubSection->SetInt("SkillSlot0", m_iMarineSkill[MarineID][ASW_SKILL_SLOT_0]);
		pSubSection->SetInt("SkillSlot1", m_iMarineSkill[MarineID][ASW_SKILL_SLOT_1]);
		pSubSection->SetInt("SkillSlot2", m_iMarineSkill[MarineID][ASW_SKILL_SLOT_2]);
		pSubSection->SetInt("SkillSlot3", m_iMarineSkill[MarineID][ASW_SKILL_SLOT_3]);
		pSubSection->SetInt("SkillSlot4", m_iMarineSkill[MarineID][ASW_SKILL_SLOT_4]);
		pSubSection->SetInt("SkillSlotSpare", m_iMarineSkill[MarineID][ASW_SKILL_SLOT_SPARE]);

		pSubSection->SetInt("UndoSkillSlot0", m_iPreviousMarineSkill[MarineID][ASW_SKILL_SLOT_0]);
		pSubSection->SetInt("UndoSkillSlot1", m_iPreviousMarineSkill[MarineID][ASW_SKILL_SLOT_1]);
		pSubSection->SetInt("UndoSkillSlot2", m_iPreviousMarineSkill[MarineID][ASW_SKILL_SLOT_2]);
		pSubSection->SetInt("UndoSkillSlot3", m_iPreviousMarineSkill[MarineID][ASW_SKILL_SLOT_3]);
		pSubSection->SetInt("UndoSkillSlot4", m_iPreviousMarineSkill[MarineID][ASW_SKILL_SLOT_4]);
		pSubSection->SetInt("UndoSkillSlotSpare", m_iPreviousMarineSkill[MarineID][ASW_SKILL_SLOT_SPARE]);
		
		pSubSection->SetInt("ParasitesKilled", m_iParasitesKilled[MarineID]);
		pSubSection->SetString("MissionsCompleted", STRING(m_MissionsCompleteNames[MarineID]));
		pSubSection->SetString("Medals", STRING(m_Medals[MarineID]));

		int iWound = IsMarineWounded(MarineID) ? 1 : 0;		
		pSubSection->SetInt("Wounded", iWound);
		int iDead = IsMarineAlive(MarineID) ? 0 : 1;
		pSubSection->SetInt("Dead", iDead);

		pSaveKeyValues->AddSubKey(pSubSection);
	}

	// check for any new players to add to our list
	for ( int i = 1; i <= gpGlobals->maxClients; i++ )
	{
		CASW_Player* pPlayer = dynamic_cast<CASW_Player*>(UTIL_PlayerByIndex(i));

		if ( pPlayer )
		{
			// first check his network ID
			const char *pszNetworkID = pPlayer->GetASWNetworkID();
			// check if it's in our list
			bool bFound = false;
			for (int k=0;k<m_PlayerIDs.Count();k++)
			{
				const char *p = STRING(m_PlayerIDs[k]);
				if (!Q_strcmp(p, pszNetworkID))
					bFound = true;
			}
			if (!bFound)
			{
				// add it to the list
				string_t stringID = AllocPooledString(pszNetworkID);
				m_PlayerIDs.AddToTail(stringID);
			}

			// then check player name
			const char *pszPlayerName = pPlayer->GetPlayerName();
			bFound = false;
			for (int k=0;k<m_PlayerNames.Count();k++)
			{
				const char *p = STRING(m_PlayerNames[k]);
				if (!Q_strcmp(p, pszPlayerName))
					bFound = true;
			}
			if (!bFound)
			{
				// add it to the list
				string_t stringName = AllocPooledString(pszPlayerName);
				m_PlayerNames.AddToTail(stringName);				
			}
		}
	}

	pSaveKeyValues->SetInt("NumPlayers", m_PlayerNames.Count());	
	
	// write out player names
	for (int i=0; i<m_PlayerNames.Count(); i++)
	{
		pSubSection = new KeyValues("PLAYER");		
		pSubSection->SetString("PlayerName", STRING(m_PlayerNames[i]));
		pSaveKeyValues->AddSubKey(pSubSection);
	}
	// write out player IDs
	for (int i=0; i<m_PlayerIDs.Count(); i++)
	{
		pSubSection = new KeyValues("DATA");		
		pSubSection->SetString("DataBlock", STRING(m_PlayerIDs[i]));
		pSaveKeyValues->AddSubKey(pSubSection);
	}
	// write out last commanders section
	pSubSection = new KeyValues("COMM");
	for (int i=0;i<ASW_NUM_MARINE_PROFILES;i++)
	{
		char buffer[16];
		Q_snprintf(buffer, sizeof(buffer), "Comm%d", i);
		pSubSection->SetString(buffer, STRING(m_LastCommanders[i]));		
		Q_snprintf(buffer, sizeof(buffer), "Slot%d", i);
		pSubSection->SetInt( buffer, m_LastMarineResourceSlot[i] );
			
		//Ch1ckensCoop: Record which marine was primary for reservations.
		Q_snprintf(buffer, sizeof(buffer), "Primary%d", i);
		pSubSection->SetBool( buffer, m_LastPrimaryMarines[i] );
	}
	pSaveKeyValues->AddSubKey(pSubSection);

	if (pSaveKeyValues->SaveToFile(filesystem, szFullFileName))
	{
		if (missionchooser && missionchooser->LocalMissionSource())
		{
			const char *pszNoPathName = Q_UnqualifiedFileName(szFullFileName);
			missionchooser->LocalMissionSource()->OnSaveUpdated(pszNoPathName);
		}
		
		return true;
	}
	return false;
}
Пример #13
0
void WritePHXFile( const char *pName, const phyfile_t &file )
{
	if ( file.header.size != sizeof(file.header) || file.collide.solidCount <= 0 )
		return;

	CUtlBuffer out;

	char outName[1024];
	Q_snprintf( outName, sizeof(outName), "%s", pName );
	Q_SetExtension( outName, ".phx", sizeof(outName) );

	simplifyparams_t params;
	params.Defaults();
	params.tolerance = (file.collide.solidCount > 1) ? 4.0f : 2.0f;
	// single solids constraint to AABB for placement help
	params.addAABBToSimplifiedHull = (file.collide.solidCount == 1) ? true : false;
	params.mergeConvexElements = true;
	params.mergeConvexTolerance = 0.025f;
	Q_FixSlashes(outName);
	Q_strlower(outName);
	char *pSearch = Q_strstr( outName,"models\\" );
	if ( pSearch )
	{
		char keyname[1024];
		pSearch += strlen("models\\");
		Q_StripExtension( pSearch, keyname, sizeof(keyname) );
		OverrideDefaultsForModel( keyname, params );
	}
	out.Put( &file.header, sizeof(file.header) );
	int outSize = 0;
	bool bStoreSolidNames = file.collide.solidCount > 1 ? true : false;
	bStoreSolidNames = bStoreSolidNames || HasMultipleBones(outName);

	vcollide_t *pNewCollide = ConvertVCollideToPHX( &file.collide, params, &outSize, false, bStoreSolidNames);
	g_TotalOut += file.fileSize;
	for ( int i = 0; i < pNewCollide->solidCount; i++ )
	{
		int collideSize = physcollision->CollideSize( pNewCollide->solids[i] );
		out.PutInt( collideSize );
		char *pMem = new char[collideSize];
		physcollision->CollideWrite( pMem, pNewCollide->solids[i] );
		out.Put( pMem, collideSize );
		delete[] pMem;
	}

	if (!g_bQuiet)
	{
		Msg("%s Compressed %d (%d text) to %d (%d text)\n", outName, file.fileSize, file.collide.descSize, out.TellPut(), pNewCollide->descSize );
	}
	out.Put( pNewCollide->pKeyValues, pNewCollide->descSize );
	g_TotalCompress += out.TellPut();

#if 0
	//Msg("OLD:\n-----------------------------------\n%s\n", file.collide.pKeyValues );
	CPackedPhysicsDescription *pPacked = physcollision->CreatePackedDesc( pNewCollide->pKeyValues, pNewCollide->descSize );
	Msg("NEW:\n-----------------------------------\n" );
	for ( int i = 0; i < pPacked->m_solidCount; i++ )
	{
		solid_t solid;
		pPacked->GetSolid( &solid, i );
		Msg("index %d\n", solid.index );
		Msg("name %s\n", solid.name );
		Msg("mass %.2f\n", solid.params.mass );
		Msg("surfaceprop %s\n", solid.surfaceprop);
		Msg("damping %.2f\n", solid.params.damping );
		Msg("rotdamping %.2f\n", solid.params.rotdamping );
		Msg("drag %.2f\n", solid.params.dragCoefficient );
		Msg("inertia %.2f\n", solid.params.inertia );
		Msg("volume %.2f\n", solid.params.volume );
	}
#endif
	DestroyPHX( pNewCollide );
	if ( !g_pFullFileSystem->WriteFile( outName, NULL, out ) )
		Warning("Can't write file: %s\n", outName );
}
Пример #14
0
//-----------------------------------------------------------------------------
// Saves/loads from file
//-----------------------------------------------------------------------------
bool CVcdBlockDoc::LoadFromFile( const char *pFileName )
{
	Assert( !m_hVMFRoot.Get() );
	Assert( !m_hEditRoot.Get() );

	CAppDisableUndoScopeGuard guard( "CVcdBlockDoc::LoadFromFile", NOTIFY_CHANGE_OTHER );
	SetDirty( false );

	if ( !pFileName[0] )
		return false;

	// Construct VMF file name from the BSP
	const char *pGame = Q_stristr( pFileName, "\\game\\" );
	if ( !pGame )
	{
		pGame = Q_stristr( pFileName, "\\content\\" );
		if ( !pGame )
			return false;
	}

	// Compute the map name
	const char *pMaps = Q_stristr( pFileName, "\\maps\\" );
	if ( !pMaps )
		return false;

	// Build map name
	char mapname[ 256 ];
	Q_StripExtension( pFileName, mapname, sizeof(mapname) );
	char *pszFileName = (char*)Q_UnqualifiedFileName(mapname);

	int nLen = (int)( (size_t)pGame - (size_t)pFileName ) + 1;
	Q_strncpy( m_pVMFFileName, pFileName, nLen );
	Q_strncat( m_pVMFFileName, "\\content\\", sizeof(m_pVMFFileName) );
	Q_strncat( m_pVMFFileName, pGame + 6, sizeof(m_pVMFFileName) );
	Q_SetExtension( m_pVMFFileName, ".vmf", sizeof(m_pVMFFileName) );

	// Make sure new entities start with ids at 0
	CDmeVMFEntity::SetNextEntityId( 0 );

	// Build the Edit file name
	Q_StripExtension( m_pVMFFileName, m_pEditFileName, sizeof(m_pEditFileName) );
	Q_strncat( m_pEditFileName, ".vle", sizeof( m_pEditFileName ) );

	// Store the BSP file name
	Q_strncpy( m_pBSPFileName, pFileName, sizeof( m_pBSPFileName ) );

	// Set the txt file name. 
	// If we loaded a .bsp, clear out what we're doing
	// load the Edits file into memory, assign it as our "root"
	CDmElement *pEdit = NULL;
	if ( !V_stricmp( Q_GetFileExtension( pFileName ), "vle" ) )
	{
		if ( g_pDataModel->RestoreFromFile( m_pEditFileName, NULL, "vmf", &pEdit ) != DMFILEID_INVALID )
		{
			// If we successfully read the file in, ask it for the max hammer id
			//int nMaxHammerId = pVMF->GetAttributeValue<int>( "maxHammerId" );
			//CDmeVMFEntity::SetNextEntityId( nMaxHammerId + 1 );
			m_hEditRoot = pEdit;
			SetDirty( false );
		}
	}

	if (pEdit == NULL)
	{
		if ( g_pFileSystem->FileExists( m_pEditFileName ) )
		{
			char pBuf[1024];
			Q_snprintf( pBuf, sizeof(pBuf), "File %s already exists!\n", m_pEditFileName ); 
			m_pEditFileName[0] = 0;
			vgui::MessageBox *pMessageBox = new vgui::MessageBox( "Unable to overwrite file!\n", pBuf, g_pVcdBlockTool );
			pMessageBox->DoModal( );
			return false;
		}

		DmFileId_t fileid = g_pDataModel->FindOrCreateFileId( m_pEditFileName );
		m_hEditRoot = CreateElement<CDmElement>( "root", fileid );
		m_hEditRoot->AddAttribute( "entities", AT_ELEMENT_ARRAY );
		g_pDataModel->SetFileRoot( fileid, m_hEditRoot );
		SetDirty( true );
	}

	guard.Release();

	// tell the engine to actually load the map
	char cmd[ 256 ];
	Q_snprintf( cmd, sizeof( cmd ), "disconnect; map %s\n", pszFileName );
	enginetools->Command( cmd );
	enginetools->Execute( );

	return true;
}
Пример #15
0
	virtual int Run()
	{
		while ( true )
		{
			WaitForCall();

			if ( GetCallParam() == MBC_SHUTDOWN )
			{
				// exit cleanly
				return 0;
			}
			else
			{
#ifdef SUPPORT_VBSP_2
				char filename[MAX_PATH];
				// Safe to access m_szVBSP2MapName because it will not be changed by the main thread while this is happening.
				Q_snprintf( filename, sizeof( filename ), "maps\\%s", m_pMapBuilder->m_szVBSP2MapName );
				CSimpleMapFile *pSimpleMapFile;
				m_pMapBuilder->m_nVBSP2Progress = g_ProgressAmounts[1];
				CSimpleMapFile::LoadFromFile( g_pFullFileSystem, filename, &pSimpleMapFile );
				m_pMapBuilder->m_nVBSP2Progress = g_ProgressAmounts[2];
				pSimpleMapFile->ResolveInstances( CSimpleMapFile::CONVERT_STRUCTURAL_TO_DETAIL, FixupInstance, m_pMapBuilder );
				m_pMapBuilder->m_nVBSP2Progress = g_ProgressAmounts[3];

				// mess with the pSimpleMapFile here
				/*
				CMapLayout *pLayout = m_pMapBuilder->GetCurrentlyBuildingMapLayout();
				
				// find the alien floor texture
				int iBrushes = pSimpleMapFile->GetBrushCount();
				const MapBrush_t *pBrushes = pSimpleMapFile->GetBrushes();
				const MapBrushSide_t *pBrushSides = pSimpleMapFile->GetBrushSides();
				MapTextureInfo_t *pTextureInfos = pSimpleMapFile->GetTextureInfos();
				MapTextureData_t *pTextureDatas = pSimpleMapFile->GetTextureData();
				const MapTextureInfo_t *pAlienFloorTextureInfo = NULL;			// a texture info that's using the alien floor material
				for ( int i = 0; i < iBrushes; i++ )
				{
					for ( int side = pBrushes[i].m_nFirstSideIndex; side < pBrushes[i].m_nFirstSideIndex + pBrushes[i].m_nNumSides; side++ )
					{
						const MapTextureInfo_t *pTextureInfo = &pTextureInfos[ pBrushSides[ side ].m_nTextureInfoIndex ];
						const MapTextureData_t *pTextureData = &pTextureDatas[ pTextureInfo->m_nTextureDataIndex ];
						if ( !Q_stricmp( pTextureData->m_MaterialName, asw_alien_floor_texture.GetString() ) )
						{
							pAlienFloorTextureInfo = pTextureInfo;
							break;
						}
					}
				}

				if ( pAlienFloorTextureInfo )
				{
					// now find all sides using the regular floor texture
					for ( int i = 0; i < iBrushes; i++ )
					{
						// is this brush in an encounter room? - just check the center for now
						Vector vecCenter = ( pBrushes[i].m_vMinBounds + pBrushes[i].m_vMaxBounds ) * 0.5f;
						CRoom *pRoom = pLayout->GetRoom( vecCenter );
						if ( !pRoom || !pRoom->HasAlienEncounter() )
							continue;

						for ( int side = pBrushes[i].m_nFirstSideIndex; side < pBrushes[i].m_nFirstSideIndex + pBrushes[i].m_nNumSides; side++ )
						{
							MapTextureInfo_t *pTextureInfo = &pTextureInfos[ pBrushSides[ side ].m_nTextureInfoIndex ];
							MapTextureData_t *pTextureData = &pTextureDatas[ pTextureInfo->m_nTextureDataIndex ];
							if ( !Q_stricmp( pTextureData->m_MaterialName, asw_regular_floor_texture.GetString() ) )
							{
								// switch regular floor over to using the new texture index
								pTextureInfo->m_nTextureDataIndex = pAlienFloorTextureInfo->m_nTextureDataIndex;
							}
						}
					}
				}
				else
				{
					Warning( "Couldn't find alien floor texture in map\n" );
				}
				*/

				// re-resolve if necessary
				//pSimpleMapFile->ResolveInstances( CSimpleMapFile::CONVERT_STRUCTURAL_TO_DETAIL, NULL, NULL );

				char bspFilename[MAX_PATH];
				Q_strncpy( bspFilename, filename, MAX_PATH );
				Q_SetExtension( bspFilename, ".bsp", MAX_PATH );
				CUtlStreamBuffer outputBSPFile( bspFilename, NULL );
				CSimpleBSPFile *pBSPFile = new CSimpleBSPFile();
				pBSPFile->CreateFromMapFile( pSimpleMapFile );
				m_pMapBuilder->m_nVBSP2Progress = g_ProgressAmounts[4];
				SaveToFile( &outputBSPFile, pBSPFile );
				outputBSPFile.Close();
				delete pBSPFile;
				delete pSimpleMapFile;

				// Commit all reads/writes before ending task
				ThreadMemoryBarrier();
				m_pMapBuilder->m_nVBSP2Progress = g_ProgressAmounts[5];

				Reply( 0 );
#else
				return 0;
#endif
			}
		}
		return 0;
	}
Пример #16
0
// Builds a map from a .layout file
void CASW_Map_Builder::BuildMap()
{
	char layoutFilename[MAX_PATH];
	char vmfFilename[MAX_PATH];
	
	Q_snprintf( layoutFilename, MAX_PATH, "maps\\%s", m_szLayoutName );
	Q_strncpy( vmfFilename, m_szLayoutName, MAX_PATH );
	Q_SetExtension( vmfFilename, "vmf", MAX_PATH );

	Log_Msg( LOG_TilegenGeneral, "Building map from layout: %s, emitting map file: %s\n", layoutFilename, vmfFilename );

	// Make sure our themes are loaded
	CLevelTheme::LoadLevelThemes();

	// Load the .layout from disk
	// @TODO: keep this in memory and avoid the round-trip
	delete m_pBuildingMapLayout;
	m_pBuildingMapLayout = new CMapLayout();
	if ( !m_pBuildingMapLayout->LoadMapLayout( layoutFilename ) )
	{
		Log_Warning(LOG_TilegenGeneral, "Couldn't find layoutfile: [%s]", layoutFilename);
		m_iBuildStage = MapBuildStage::STAGE_NONE;
		delete m_pBuildingMapLayout;
		m_pBuildingMapLayout = NULL;
		return;
	}

	// Export it to VMF
	bool bSuccess = false;
	{
		VMFExporter exporter;
		bSuccess = exporter.ExportVMF(m_pBuildingMapLayout, m_szLayoutName);
	}

	if ( !bSuccess )
	{
		Log_Warning( LOG_TilegenGeneral, "Failed to create VMF from layout '%s'.\n", m_szLayoutName );
		delete m_pBuildingMapLayout;
		m_pBuildingMapLayout = NULL;
	}
	
	if ( asw_vbsp2.GetInt() )
	{
		m_iBuildStage = STAGE_VBSP2;
		m_nVBSP2Progress = 0;
		Q_strncpy( m_szVBSP2MapName, vmfFilename, MAX_PATH );
		// Guarantee all reads/writes committed before kicking off the thread.  Probably unnecessary in practice due to lag between operations, but whatever...
		ThreadMemoryBarrier();

		// Call with a 0 ms timeout to return immediately
		m_pWorkerThread->CallWorker( MBC_PROCESS_MAP, 0 );
	}
	else
	{
		// Building map layout is ignored in VBSP1 codepath
		delete m_pBuildingMapLayout;
		m_pBuildingMapLayout = NULL;

		m_iBuildStage = STAGE_VBSP;

		char buffer[512];
		Q_snprintf( buffer, sizeof(buffer), "-game ..\\ %s %s", m_pMapBuilderOptions->GetString( "vbsp", "" ), vmfFilename );
		Execute( "bin/vbsp.exe", buffer );

		m_iCurrentBuildSearch = 0;
		m_iOutputBufferPos = 0;
		Q_memset( &m_szOutputBuffer, 0, sizeof( m_szOutputBuffer ) );
	}
}
Пример #17
0
//-----------------------------------------------------------------------------
// Load the VMF file, merge in all the edits, write it back out
//-----------------------------------------------------------------------------
bool CVcdBlockDoc::CopyEditsToVMF( )
{
	const CDmrElementArray<CDmElement> entityList = GetEntityList();
	
	CDmElement *pVMF = NULL;
	DmFileId_t fileid = g_pDataModel->FindOrCreateFileId( m_pVMFFileName );
	if ( g_pDataModel->RestoreFromFile( m_pVMFFileName, NULL, "vmf", &pVMF ) == DMFILEID_INVALID )
	{
		// needs some kind of error message
		return false;
	}

	CDmrElementArray<CDmElement> vmfEntities( pVMF, "entities" );

	int nVMFCount = vmfEntities.Count();
	for (int i = 0; i < nVMFCount; i++)
	{
		CDmElement *pVMFEntity = vmfEntities[i];

		char classname[256];
		pVMFEntity->GetValueAsString( "classname", classname, sizeof( classname ) );

		if ( Q_stricmp( "info_target", classname ) )
			continue;

		int nHammerID = atoi( pVMFEntity->GetName() );

		// find a match.
		int nCount = entityList.Count();
		for (int j = 0; j < nCount; j++)
		{
			CDmeVMFEntity *pEntity = CastElement<CDmeVMFEntity>( entityList[j] );

			if ( pEntity->IsDirty() && pEntity->GetEntityId() == nHammerID)
			{
				char text[256];
				pEntity->GetValueAsString( "targetname", text, sizeof( text ) );
				pVMFEntity->SetValueFromString( "targetname", text );
				pEntity->GetValueAsString( "origin", text, sizeof( text ) );
				pVMFEntity->SetValueFromString( "origin", text );
				pEntity->GetValueAsString( "angles", text, sizeof( text ) );
				pVMFEntity->SetValueFromString( "angles", text );

				pEntity->MarkDirty(false);
			}
		}
	}

	// add the new entities
	int nCount = entityList.Count();
	for (int j = 0; j < nCount; j++)
	{
		CDmeVMFEntity *pEntity = CastElement<CDmeVMFEntity>( entityList[j] );

		if ( pEntity->IsDirty())
		{
			CDmElement *pVMFEntity = CreateElement<CDmElement>( pEntity->GetName(), fileid );

			char text[256];
			pEntity->GetValueAsString( "classname", text, sizeof( text ) );
			pVMFEntity->SetValue( "classname", text );
			pEntity->GetValueAsString( "targetname", text, sizeof( text ) );
			pVMFEntity->SetValue( "targetname", text );
			pEntity->GetValueAsString( "origin", text, sizeof( text ) );
			pVMFEntity->SetValue( "origin", text );
			pEntity->GetValueAsString( "angles", text, sizeof( text ) );
			pVMFEntity->SetValue( "angles", text );

			vmfEntities.AddToTail( pVMFEntity );

			pEntity->MarkDirty(false);
		}
	}

	// currently, don't overwrite the vmf, not sure if this is serializing correctly yet
	char tmpname[ 256 ];
	Q_StripExtension( m_pVMFFileName, tmpname, sizeof(tmpname) );
	Q_SetExtension( tmpname, ".vme", sizeof(tmpname) );

	if (!g_pDataModel->SaveToFile( tmpname, NULL, "keyvalues", "vmf", pVMF ))
	{
		// needs some kind of error message
		return false;
	}

	/*
		// If we successfully read the file in, ask it for the max hammer id
		int nMaxHammerId = pVMF->GetAttributeValue<int>( "maxHammerId" );
		CDmeVMFEntity::SetNextEntityId( nMaxHammerId + 1 );
		m_hVMFRoot = pVMF;
	*/

	return true;
}
Пример #18
0
bool CEngineSprite::Init( const char *pName )
{
	m_hAVIMaterial = AVIMATERIAL_INVALID;
	m_hBIKMaterial = BIKMATERIAL_INVALID;
	m_width = m_height = m_numFrames = 1;

	const char *pExt = Q_GetFileExtension( pName );
	bool bIsAVI = pExt && !Q_stricmp( pExt, "avi" );
#if !defined( _X360 ) || defined( BINK_ENABLED_FOR_X360 )
	bool bIsBIK = pExt && !Q_stricmp( pExt, "bik" );
#endif
	if ( bIsAVI && IsPC() )
	{
		m_hAVIMaterial = avi->CreateAVIMaterial( pName, pName, "GAME" );
		if ( m_hAVIMaterial == AVIMATERIAL_INVALID )
			return false;

		IMaterial *pMaterial = avi->GetMaterial( m_hAVIMaterial );
		avi->GetFrameSize( m_hAVIMaterial, &m_width, &m_height );
		m_numFrames = avi->GetFrameCount( m_hAVIMaterial );
		for ( int i = 0; i < kRenderModeCount; ++i )
		{
			m_material[i] = pMaterial;
			pMaterial->IncrementReferenceCount();
		}
	}
#if !defined( _X360 ) || defined( BINK_ENABLED_FOR_X360 )
	else if ( bIsBIK )
	{
		m_hBIKMaterial = bik->CreateMaterial( pName, pName, "GAME" );
		if ( m_hBIKMaterial == BIKMATERIAL_INVALID )
			return false;

		IMaterial *pMaterial = bik->GetMaterial( m_hBIKMaterial );
		bik->GetFrameSize( m_hBIKMaterial, &m_width, &m_height );
		m_numFrames = bik->GetFrameCount( m_hBIKMaterial );
		for ( int i = 0; i < kRenderModeCount; ++i )
		{
			m_material[i] = pMaterial;
			pMaterial->IncrementReferenceCount();
		}
	}
#endif
	else
	{
		char pTemp[MAX_PATH];
		char pMaterialName[MAX_PATH];
		char pMaterialPath[MAX_PATH];
		Q_StripExtension( pName, pTemp, sizeof(pTemp) );
		Q_strlower( pTemp );
		Q_FixSlashes( pTemp, '/' );

		// Check to see if this is a UNC-specified material name
		bool bIsUNC = pTemp[0] == '/' && pTemp[1] == '/' && pTemp[2] != '/';
		if ( !bIsUNC )
		{
			Q_strncpy( pMaterialName, "materials/", sizeof(pMaterialName) );
			Q_strncat( pMaterialName, pTemp, sizeof(pMaterialName), COPY_ALL_CHARACTERS );
		}
		else
		{
			Q_strncpy( pMaterialName, pTemp, sizeof(pMaterialName) );
		}
		Q_strncpy( pMaterialPath, pMaterialName, sizeof(pMaterialPath) );
		Q_SetExtension( pMaterialPath, ".vmt", sizeof(pMaterialPath) );

		for ( int i = 0; i < kRenderModeCount; ++i )
		{	
			m_material[i] = NULL;
		}

		KeyValues *kv = new KeyValues( "vmt" );
		if ( !kv->LoadFromFile( g_pFullFileSystem, pMaterialPath, "GAME" ) )
		{
			Warning( "Unable to load sprite material %s!\n", pMaterialPath );
			return false;
		}

		for ( int i = 0; i < kRenderModeCount; ++i )
		{	
			if ( i == kRenderNone || i == kRenderEnvironmental )
			{
				continue;
			}

			// strip possible materials/
			Q_snprintf( pMaterialPath, sizeof(pMaterialPath), "%s_rendermode_%d", pMaterialName + ( bIsUNC ? 0 : 10 ), i );
			KeyValues *pMaterialKV = kv->MakeCopy();
			pMaterialKV->SetInt( "$spriteRenderMode", i );
			m_material[i] = g_pMaterialSystem->FindProceduralMaterial( pMaterialPath, TEXTURE_GROUP_CLIENT_EFFECTS, pMaterialKV );
			m_material[i]->IncrementReferenceCount();	
		}

		kv->deleteThis();

		m_width = m_material[0]->GetMappingWidth();
		m_height = m_material[0]->GetMappingHeight();
		m_numFrames = m_material[0]->GetNumAnimationFrames();
	}

	for ( int i = 0; i < kRenderModeCount; ++i )
	{
		if ( i == kRenderNone || i == kRenderEnvironmental )
			continue;

		if ( !m_material[i] )
			return false;
	}

	IMaterialVar *orientationVar = m_material[0]->FindVarFast( "$spriteorientation", &spriteOrientationCache );
	m_orientation = orientationVar ? orientationVar->GetIntValue() : C_SpriteRenderer::SPR_VP_PARALLEL_UPRIGHT;

	IMaterialVar *originVar = m_material[0]->FindVarFast( "$spriteorigin", &spriteOriginCache );
	Vector origin, originVarValue;
	if( !originVar || ( originVar->GetType() != MATERIAL_VAR_TYPE_VECTOR ) )
	{
		origin[0] = -m_width * 0.5f;
		origin[1] = m_height * 0.5f;
	}
	else
	{
		originVar->GetVecValue( &originVarValue[0], 3 );
		origin[0] = -m_width * originVarValue[0];
		origin[1] = m_height * originVarValue[1];
	}

	up = origin[1];
	down = origin[1] - m_height;
	left = origin[0];
	right = m_width + origin[0];

	return true;
}
Пример #19
0
bool CEngineSprite::Init( const char *pName )
{
	m_VideoMaterial = NULL;
	for ( int i = 0; i < kRenderModeCount; ++i )
	{
		m_material[ i ] = NULL;
	}

	m_width = m_height = m_numFrames = 1;

	Assert( g_pVideo != NULL );
	
	if ( g_pVideo != NULL && g_pVideo->LocateVideoSystemForPlayingFile( pName ) != VideoSystem::NONE ) 
	{
		m_VideoMaterial = g_pVideo->CreateVideoMaterial( pName, pName, "GAME", VideoPlaybackFlags::DEFAULT_MATERIAL_OPTIONS, VideoSystem::DETERMINE_FROM_FILE_EXTENSION, false ); 
		
		if ( m_VideoMaterial == NULL )
			return false;

		IMaterial *pMaterial = m_VideoMaterial->GetMaterial();
		m_VideoMaterial->GetVideoImageSize( &m_width, &m_height );
		m_numFrames = m_VideoMaterial->GetFrameCount();
		for ( int i = 0; i < kRenderModeCount; ++i )
		{
			m_material[i] = pMaterial;
			pMaterial->IncrementReferenceCount();
		}
	}
	else
	{
		char pTemp[MAX_PATH];
		char pMaterialName[MAX_PATH];
		char pMaterialPath[MAX_PATH];
		Q_StripExtension( pName, pTemp, sizeof(pTemp) );
		Q_strlower( pTemp );
		Q_FixSlashes( pTemp, '/' );

		// Check to see if this is a UNC-specified material name
		bool bIsUNC = pTemp[0] == '/' && pTemp[1] == '/' && pTemp[2] != '/';
		if ( !bIsUNC )
		{
			Q_strncpy( pMaterialName, "materials/", sizeof(pMaterialName) );
			Q_strncat( pMaterialName, pTemp, sizeof(pMaterialName), COPY_ALL_CHARACTERS );
		}
		else
		{
			Q_strncpy( pMaterialName, pTemp, sizeof(pMaterialName) );
		}
		Q_strncpy( pMaterialPath, pMaterialName, sizeof(pMaterialPath) );
		Q_SetExtension( pMaterialPath, ".vmt", sizeof(pMaterialPath) );

		KeyValues *kv = new KeyValues( "vmt" );
		if ( !kv->LoadFromFile( g_pFullFileSystem, pMaterialPath, "GAME" ) )
		{
			Warning( "Unable to load sprite material %s!\n", pMaterialPath );
			return false;
		}

		for ( int i = 0; i < kRenderModeCount; ++i )
		{	
			if ( i == kRenderNone || i == kRenderEnvironmental )
			{
				m_material[i] = NULL;
				continue;
			}

			Q_snprintf( pMaterialPath, sizeof(pMaterialPath), "%s_rendermode_%d", pMaterialName, i );
			KeyValues *pMaterialKV = kv->MakeCopy();
			pMaterialKV->SetInt( "$spriteRenderMode", i );
			m_material[i] = g_pMaterialSystem->FindProceduralMaterial( pMaterialPath, TEXTURE_GROUP_CLIENT_EFFECTS, pMaterialKV );
			m_material[ i ]->IncrementReferenceCount();
		}

		kv->deleteThis();

		m_width = m_material[0]->GetMappingWidth();
		m_height = m_material[0]->GetMappingHeight();
		m_numFrames = m_material[0]->GetNumAnimationFrames();
	}

	for ( int i = 0; i < kRenderModeCount; ++i )
	{
		if ( i == kRenderNone || i == kRenderEnvironmental )
			continue;

		if ( !m_material[i] )
			return false;
	}

	IMaterialVar *orientationVar = m_material[0]->FindVarFast( "$spriteorientation", &spriteOrientationCache );
	m_orientation = orientationVar ? orientationVar->GetIntValue() : C_SpriteRenderer::SPR_VP_PARALLEL_UPRIGHT;

	IMaterialVar *originVar = m_material[0]->FindVarFast( "$spriteorigin", &spriteOriginCache );
	Vector origin, originVarValue;
	if( !originVar || ( originVar->GetType() != MATERIAL_VAR_TYPE_VECTOR ) )
	{
		origin[0] = -m_width * 0.5f;
		origin[1] = m_height * 0.5f;
	}
	else
	{
		originVar->GetVecValue( &originVarValue[0], 3 );
		origin[0] = -m_width * originVarValue[0];
		origin[1] = m_height * originVarValue[1];
	}

	up = origin[1];
	down = origin[1] - m_height;
	left = origin[0];
	right = m_width + origin[0];

	return true;
}
Пример #20
0
// reads in current save data from a keyvalues file
bool CASW_Campaign_Save::LoadGameFromFile(const char *szFileName)
{
	// make sure the path and extension are correct
	char szFullFileName[256];
	char tempbuffer[256];
	Q_snprintf(tempbuffer, sizeof(tempbuffer), "%s", szFileName);	
	Q_SetExtension( tempbuffer, ".campaignsave", sizeof(tempbuffer) );
	const char *pszNoPathName = Q_UnqualifiedFileName(tempbuffer);	
	Q_snprintf(szFullFileName, sizeof(szFullFileName), "save/%s", pszNoPathName);	

	KeyValues *pSaveKeyValues = new KeyValues( szFileName );
	if (pSaveKeyValues->LoadFromFile(filesystem, szFullFileName))
	{
		m_CurrentSaveFileName = AllocPooledString(szFullFileName);

		m_iVersion = pSaveKeyValues->GetInt("Version");		
		m_iLowestSkillLevelPlayed = pSaveKeyValues->GetInt("SkillLevel");
		Q_strncpy( m_CampaignName.GetForModify(), pSaveKeyValues->GetString("CampaignName"), 255 );
		m_iCurrentPosition = pSaveKeyValues->GetInt("CurrentPosition");
		m_iNumMissionsComplete = pSaveKeyValues->GetInt("NumMissionsComplete");
		m_iInitialNumMissionsComplete = pSaveKeyValues->GetInt("InitialNumMissionsComplete");
		m_bMultiplayerGame = pSaveKeyValues->GetInt("Multiplayer") != 0;		
		Q_strncpy( m_DateTime.GetForModify(), pSaveKeyValues->GetString("DateTime"), 255 );		
		m_iNumDeaths = pSaveKeyValues->GetInt("NumDeaths");
		m_bFixedSkillPoints = !asw_custom_skill_points.GetBool(); //pSaveKeyValues->GetBool( "FixedSkillPoints", true );
		
		m_iNumPlayers = pSaveKeyValues->GetInt("NumPlayers");
		m_PlayerNames.Purge();
		m_PlayerIDs.Purge();

		// go through each sub section, adding the relevant details
		KeyValues *pkvSubSection = pSaveKeyValues->GetFirstSubKey();
		while ( pkvSubSection )
		{
			// mission details
			if (Q_stricmp(pkvSubSection->GetName(), "MISSION")==0)
			{
				int MissionID = pkvSubSection->GetInt("MissionID");
				if (MissionID >=0 && MissionID < ASW_MAX_MISSIONS_PER_CAMPAIGN)
				{
					m_MissionComplete.Set(MissionID, pkvSubSection->GetInt("MissionComplete"));
					m_NumRetries.Set(MissionID, pkvSubSection->GetInt("NumRetries"));
				}
			}

			// marine details
			if (Q_stricmp(pkvSubSection->GetName(), "MARINE")==0)
			{
				int MarineID = pkvSubSection->GetInt("MarineID");
				if (MarineID >=0 && MarineID < ASW_NUM_MARINE_PROFILES)
				{
					m_iMarineSkill[MarineID][ASW_SKILL_SLOT_0] = pkvSubSection->GetInt("SkillSlot0");
					m_iMarineSkill[MarineID][ASW_SKILL_SLOT_1] = pkvSubSection->GetInt("SkillSlot1");
					m_iMarineSkill[MarineID][ASW_SKILL_SLOT_2] = pkvSubSection->GetInt("SkillSlot2");
					m_iMarineSkill[MarineID][ASW_SKILL_SLOT_3] = pkvSubSection->GetInt("SkillSlot3");
					m_iMarineSkill[MarineID][ASW_SKILL_SLOT_4] = pkvSubSection->GetInt("SkillSlot4");
					m_iMarineSkill[MarineID][ASW_SKILL_SLOT_SPARE] = pkvSubSection->GetInt("SkillSlotSpare");

					m_iPreviousMarineSkill[MarineID][ASW_SKILL_SLOT_0] = pkvSubSection->GetInt("UndoSkillSlot0");
					m_iPreviousMarineSkill[MarineID][ASW_SKILL_SLOT_1] = pkvSubSection->GetInt("UndoSkillSlot1");
					m_iPreviousMarineSkill[MarineID][ASW_SKILL_SLOT_2] = pkvSubSection->GetInt("UndoSkillSlot2");
					m_iPreviousMarineSkill[MarineID][ASW_SKILL_SLOT_3] = pkvSubSection->GetInt("UndoSkillSlot3");
					m_iPreviousMarineSkill[MarineID][ASW_SKILL_SLOT_4] = pkvSubSection->GetInt("UndoSkillSlot4");
					m_iPreviousMarineSkill[MarineID][ASW_SKILL_SLOT_SPARE] = pkvSubSection->GetInt("UndoSkillSlotSpare");

					m_iParasitesKilled[MarineID] = pkvSubSection->GetInt("ParasitesKilled");

					m_MissionsCompleteNames.Set(MarineID, AllocPooledString(pkvSubSection->GetString("MissionsCompleted")));
					m_Medals.Set(MarineID, AllocPooledString(pkvSubSection->GetString("Medals")));

					m_bMarineWounded.Set(MarineID, (pkvSubSection->GetInt("Wounded") == 1));
					m_bMarineDead.Set(MarineID, (pkvSubSection->GetInt("Dead") == 1));

					//Ch1ckensCoop: Hack to give marines skill points for the first mission in a campaign. I'm too lazy to edit missionchooser.
					if (m_iCurrentPosition == 1)
					{
						m_iMarineSkill[MarineID][ASW_SKILL_SLOT_SPARE] = sk_asw_points_per_mission.GetInt();
						m_iPreviousMarineSkill[MarineID][ASW_SKILL_SLOT_SPARE] = sk_asw_points_per_mission.GetInt();
					}
				}					
			}

			// player name
			if (Q_stricmp(pkvSubSection->GetName(), "PLAYER")==0)
			{
				string_t stringName = AllocPooledString(pkvSubSection->GetString("PlayerName"));
				m_PlayerNames.AddToTail(stringName);				
			}
			// player ID
			if (Q_stricmp(pkvSubSection->GetName(), "DATA")==0)
			{
				string_t stringID = AllocPooledString(pkvSubSection->GetString("DataBlock"));
				m_PlayerIDs.AddToTail(stringID);								
			}
			// last commanders
			if (Q_stricmp(pkvSubSection->GetName(), "COMM")==0)
			{
				for (int i=0;i<ASW_NUM_MARINE_PROFILES;i++)
				{
					char buffer[16];
					Q_snprintf(buffer, sizeof(buffer), "Comm%d", i);
					string_t stringID = AllocPooledString(pkvSubSection->GetString(buffer));					
					m_LastCommanders[i] = stringID;
					Q_snprintf(buffer, sizeof(buffer), "Slot%d", i);
					m_LastMarineResourceSlot[i] = pkvSubSection->GetInt(buffer);

					//Ch1ckensCoop: Remember primary marines for each player, so we can handle reservations properly.
					Q_snprintf(buffer, sizeof(buffer), "Primary%d", i);
					m_LastPrimaryMarines[i] = pkvSubSection->GetBool(buffer);
				}				
			}
			
			pkvSubSection = pkvSubSection->GetNextKey();
		}
		return true;
	}
	Msg("Failed to load KeyValues from file %s\n", szFullFileName);
	return false;
}
Пример #21
0
bool VMFExporter::ExportVMF( CMapLayout* pLayout, const char *mapname, bool bPopupWarnings )
{
    m_bPopupWarnings = bPopupWarnings;

    Init();

    m_pMapLayout = pLayout;

    if ( pLayout->m_PlacedRooms.Count() <= 0 )
    {
        Q_snprintf( m_szLastExporterError, sizeof(m_szLastExporterError), "Failed to export: No rooms placed in the map layout!\n" );
        return false;
    }

    // see if we have a start room
    bool bHasStartRoom = false;
    for ( int i = 0 ; i < pLayout->m_PlacedRooms.Count() ; i++ )
    {
        if ( pLayout->m_PlacedRooms[i]->m_pRoomTemplate->IsStartRoom() )
        {
            int half_map_size = MAP_LAYOUT_TILES_WIDE * 0.5f;		// shift back so the middle of our grid is the origin
            m_vecStartRoomOrigin.x = ( pLayout->m_PlacedRooms[i]->m_iPosX - half_map_size ) * ASW_TILE_SIZE;
            m_vecStartRoomOrigin.y = ( pLayout->m_PlacedRooms[i]->m_iPosY - half_map_size ) * ASW_TILE_SIZE;
            bHasStartRoom = true;
            break;
        }
    }
    LoadUniqueKeyList();

    m_iNextNodeID = 0;

    m_pExportKeys = new KeyValues( "ExportKeys" );

    m_pExportKeys->AddSubKey( GetVersionInfo() );
    m_pExportKeys->AddSubKey( GetDefaultVisGroups() );
    m_pExportKeys->AddSubKey( GetViewSettings() );
    m_pExportWorldKeys = GetDefaultWorldChunk();
    if ( !m_pExportWorldKeys )
    {
        Q_snprintf( m_szLastExporterError, sizeof(m_szLastExporterError), "Failed to save world chunk start\n");
        return false;
    }
    m_pExportKeys->AddSubKey( m_pExportWorldKeys );


    // save out the big cube the whole level sits in
    if ( !AddLevelContainer() )
    {
        Q_snprintf( m_szLastExporterError, sizeof(m_szLastExporterError), "Failed to save level container\n");
        return false;
    }

    if ( tilegen_use_instancing.GetBool() )
    {
        int nLogicalRooms = m_pMapLayout->m_LogicalRooms.Count();
        int nPlacedRooms = m_pMapLayout->m_PlacedRooms.Count();

        m_pRoom = NULL;
        for ( int i = 0; i < nLogicalRooms; ++ i )
        {
            AddRoomInstance( m_pMapLayout->m_LogicalRooms[i] );
        }

        for ( int i = 0; i < nPlacedRooms; ++ i )
        {
            m_pRoom = m_pMapLayout->m_PlacedRooms[i];
            AddRoomInstance( m_pRoom->m_pRoomTemplate, i );
        }
    }
    else
    {
        // write out logical room solids
        int iLogicalRooms = m_pMapLayout->m_LogicalRooms.Count();
        m_pRoom = NULL;
        for ( int i = 0 ; i < iLogicalRooms ; i++ )
        {
            // start logical room IDs at 5000 (assumes we'll never place 5000 real rooms)
            m_iCurrentRoom = 5000 + i;
            CRoomTemplate *pRoomTemplate = m_pMapLayout->m_LogicalRooms[i];
            if ( !pRoomTemplate )
                continue;

            if ( !AddRoomTemplateSolids( pRoomTemplate ) )
                return false;
        }

        // go through each CRoom and write out its world solids
        int iRooms = m_pMapLayout->m_PlacedRooms.Count();
        for ( m_iCurrentRoom = 0 ; m_iCurrentRoom<iRooms ; m_iCurrentRoom++)
        {
            m_pRoom = m_pMapLayout->m_PlacedRooms[m_iCurrentRoom];
            if (!m_pRoom)
                continue;
            const CRoomTemplate *pRoomTemplate = m_pRoom->m_pRoomTemplate;
            if (!pRoomTemplate)
                continue;

            if ( !AddRoomTemplateSolids( pRoomTemplate ) )
                return false;
        }

        // write out logical room entities
        m_pRoom = NULL;
        for ( int i = 0 ; i < iLogicalRooms ; i++ )
        {
            // start logical room IDs at 5000 (assumes we'll never place 5000 real rooms)
            m_iCurrentRoom = 5000 + i;
            CRoomTemplate *pRoomTemplate = m_pMapLayout->m_LogicalRooms[i];
            if ( !pRoomTemplate )
                continue;

            if ( !AddRoomTemplateEntities( pRoomTemplate ) )
                return false;
        }

        // go through each CRoom and add its entities
        for ( m_iCurrentRoom = 0 ; m_iCurrentRoom<iRooms ; m_iCurrentRoom++)
        {
            m_pRoom = m_pMapLayout->m_PlacedRooms[m_iCurrentRoom];
            if (!m_pRoom)
                continue;
            const CRoomTemplate *pRoomTemplate = m_pRoom->m_pRoomTemplate;
            if (!pRoomTemplate)
                continue;

            if ( !AddRoomTemplateEntities( pRoomTemplate ) )
                return false;
        }
    }

    // add some player starts to the map in the tile the user selected
    if ( !bHasStartRoom )
    {
        m_pExportKeys->AddSubKey( GetPlayerStarts() );
    }

    m_pExportKeys->AddSubKey( GetGameRulesProxy() );
    m_pExportKeys->AddSubKey( GetDefaultCamera() );

    // save out the export keys
    char filename[512];
    Q_snprintf( filename, sizeof(filename), "maps\\%s", mapname );
    Q_SetExtension( filename, "vmf", sizeof( filename ) );
    CUtlBuffer buf( 0, 0, CUtlBuffer::TEXT_BUFFER );
    for ( KeyValues *pKey = m_pExportKeys->GetFirstSubKey(); pKey; pKey = pKey->GetNextKey() )
    {
        pKey->RecursiveSaveToFile( buf, 0 );
    }
    if ( !g_pFullFileSystem->WriteFile( filename, "GAME", buf ) )
    {
        Msg( "Failed to SaveToFile %s\n", filename );
        return false;
    }

    // save the map layout there (so the game can get information about rooms during play)
    Q_snprintf( filename, sizeof( filename ), "maps\\%s", mapname );
    Q_SetExtension( filename, "layout", sizeof( filename ) );
    if ( !m_pMapLayout->SaveMapLayout( filename ) )
    {
        Q_snprintf( m_szLastExporterError, sizeof(m_szLastExporterError), "Failed to save .layout file\n");
        return false;
    }

    return true;
}
bool CASW_Mission_Chooser_Source_Local::ASW_Campaign_CreateNewSaveGame(char *szFileName, int iFileNameMaxLen, const char *szCampaignName, bool bMultiplayerGame, const char *szStartingMission)	// szFileName arg is the desired filename or NULL for an autogenerated one.  Function sets szFileName with the filename used.
{
	if (!szFileName)
		return false;

	char stripped[MAX_PATH];
	V_StripExtension( szCampaignName, stripped, MAX_PATH );

	char szStartingMissionStripped[64];
	if ( szStartingMission )
	{
		V_StripExtension( szStartingMission, szStartingMissionStripped, sizeof( szStartingMissionStripped ) );
	}
	else
	{
		szStartingMissionStripped[0] = 0;
	}

	// check the campaign file exists
	char campbuffer[MAX_PATH];
	Q_snprintf(campbuffer, sizeof(campbuffer), "resource/campaigns/%s.txt", stripped);
	if (!g_pFullFileSystem->FileExists(campbuffer))
	{
		Msg("No such campaign: %s\n", campbuffer);
		return false;
	}

	// Get the current time and date as a string
	char szDateTime[256];
	int year, month, dayOfWeek, day, hour, minute, second;
	ASW_System_GetCurrentTimeAndDate(&year, &month, &dayOfWeek, &day, &hour, &minute, &second);
	Q_snprintf(szDateTime, sizeof(szDateTime), "%02d/%02d/%02d %02d:%02d", month, day, year, hour, minute);

	if (szFileName[0] == '\0')
	{
		// autogenerate a filename based on the current time and date
		Q_snprintf(szFileName, iFileNameMaxLen, "%s_save_%02d_%02d_%02d_%02d_%02d_%02d", stripped, year, month, day, hour, minute, second);
	}

	// make sure the path and extension are correct
	Q_SetExtension( szFileName, ".campaignsave", iFileNameMaxLen );
	char tempbuffer[256];
	Q_snprintf(tempbuffer, sizeof(tempbuffer), "%s", szFileName);
	const char *pszNoPathName = Q_UnqualifiedFileName(tempbuffer);
	Msg("Unqualified = %s\n", pszNoPathName);
	char szFullFileName[256];
	Q_snprintf(szFullFileName, sizeof(szFullFileName), "save/%s", pszNoPathName);
	Msg("Creating new save with filename: %s\n", szFullFileName);

	KeyValues *pSaveKeyValues = new KeyValues( pszNoPathName );

	int nMissionsComplete = 0;
	if ( szStartingMission && szStartingMission[0] )
	{
		KeyValues *pCampaignDetails = GetCampaignDetails( stripped );
		if ( pCampaignDetails )
		{
			int nMissionSections = 0;
			for ( KeyValues *pMission = pCampaignDetails->GetFirstSubKey(); pMission; pMission = pMission->GetNextKey() )
			{
				if ( !Q_stricmp( pMission->GetName(), "MISSION" ) )
				{
					if ( !Q_stricmp( pMission->GetString( "MapName", "" ), szStartingMissionStripped ) )
					{
						nMissionsComplete = nMissionSections - 1;		// skip first dummy mission
						break;
					}
					nMissionSections++;
				}
			}
		}
	}
	
	pSaveKeyValues->SetInt("Version", ASW_CURRENT_SAVE_VERSION);
	pSaveKeyValues->SetString("CampaignName", stripped);
	pSaveKeyValues->SetInt("CurrentPosition", nMissionsComplete + 1);		// position squad on the first uncompleted mission
	pSaveKeyValues->SetInt("NumMissionsComplete", nMissionsComplete);
	pSaveKeyValues->SetInt("InitialNumMissionsComplete", nMissionsComplete);
	pSaveKeyValues->SetInt("Multiplayer", bMultiplayerGame ? 1 : 0);
	pSaveKeyValues->SetString("DateTime", szDateTime);
	pSaveKeyValues->SetInt("NumPlayers", 0);	
	
	// write out each mission's status
	KeyValues *pSubSection;
	for (int i=0; i<ASW_MAX_MISSIONS_PER_CAMPAIGN; i++)
	{
		pSubSection = new KeyValues("MISSION");
		pSubSection->SetInt("MissionID", i);
		bool bComplete = ( i != 0 ) && ( i <= nMissionsComplete );
		pSubSection->SetInt("MissionComplete", bComplete ? 1 : 0 );
		pSaveKeyValues->AddSubKey(pSubSection);
	}

	const int nInitialSkillPoints = 0;

	// write out each marine's stats
	for (int i=0; i<ASW_NUM_MARINE_PROFILES; i++)
	{
		pSubSection = new KeyValues("MARINE");
		pSubSection->SetInt("MarineID", i);
		pSubSection->SetInt("SkillSlot0", 0);
		pSubSection->SetInt("SkillSlot1", 0);
		pSubSection->SetInt("SkillSlot2", 0);
		pSubSection->SetInt("SkillSlot3", 0);
		pSubSection->SetInt("SkillSlot4", 0);
		
		pSubSection->SetInt("SkillSlotSpare", nInitialSkillPoints + nMissionsComplete * ASW_SKILL_POINTS_PER_MISSION );

		pSubSection->SetInt("UndoSkillSlot0", 0);
		pSubSection->SetInt("UndoSkillSlot1", 0);
		pSubSection->SetInt("UndoSkillSlot2", 0);
		pSubSection->SetInt("UndoSkillSlot3", 0);
		pSubSection->SetInt("UndoSkillSlot4", 0);
		
		pSubSection->SetInt("UndoSkillSlotSpare", nInitialSkillPoints + nMissionsComplete * ASW_SKILL_POINTS_PER_MISSION );
		pSubSection->SetString("MissionsCompleted", "");
		pSubSection->SetString("Medals", "");
		pSubSection->SetInt("Wounded", 0);
		pSubSection->SetInt("Dead", 0);
		pSubSection->SetInt("ParasitesKilled", 0);
		pSaveKeyValues->AddSubKey(pSubSection);
	}
	// players section is empty at first 

	// Create the save sub-directory
	if (!g_pFullFileSystem->IsDirectory( "save", "MOD" ))
	{
		g_pFullFileSystem->CreateDirHierarchy( "save", "MOD" );
	}

	// save it
	if (pSaveKeyValues->SaveToFile(g_pFullFileSystem, szFullFileName))
	{
		// make sure our save summary list adds this to it, if needed
		Msg("New save created: %s\n", szFullFileName);
		NotifyNewSave(pszNoPathName);
		return true;
	}
	Msg("Save to file failed. Filename=%s\n", szFullFileName);
	return false;
}