Esempio n. 1
0
dsk_err_t DriveSelectPage::OpenDisc(DSK_PDRIVER *pdsk)
{
	wxString &filename = GetFilename();
	wxCharBuffer buf(filename.mb_str(wxConvUTF8));

	dsk_err_t err = dsk_open(pdsk, buf, GetType(), GetCompress());
	if (!err) 
	{
		long retries;
		if (!m_retries.ToLong(&retries)) retries = 1;

		dsk_set_retry(*pdsk, retries);
		if (GetForceHead() >= 0)
		{
			dsk_set_option(*pdsk, "HEAD", GetForceHead());
		}
		if (GetDoubleStep())
		{
			dsk_set_option(*pdsk, "DOUBLESTEP", 1);
		}
	}
	return err;
}
Esempio n. 2
0
bool ADVBLock::GetLock(uint_t n)
{
	const ADVBConfig& config = ADVBConfig::Get();
	LOCK *lock = (LOCK *)lockhash.Read(name);
	bool success = false;

	(void)config;

	if (!lock) {
		if ((lock = new LOCK) != NULL) {
			lock->filename.printf("lockfile_%s.lock", name.str());
			lock->fd = -1;
			lock->refcount = 0;

			lockhash.Insert(name, (uptr_t)lock);
		}
	}

	if (lock) {
		if (!lock->refcount) {
			AString lockfile = GetFilename(lock);

			if ((lock->fd = open(lockfile, O_CREAT | O_RDWR, (S_IRUSR | S_IWUSR))) >= 0) {
				if (flock(lock->fd, LOCK_EX) >= 0) {
					//config.logit("Acquired lock '%s' (filename '%s')\n", name.str(), lockfile.str());
					lock->refcount += n;
					success = true;
				}
				else config.logit("Failed to lock file: %s\n", strerror(errno));
			}
			else config.logit("Failed to create lockfile '%s' (%s)!  All Hell could break loose!!\n", lockfile.str(), strerror(errno));
		}
	}
	else config.logit("Failed to create lock '%s'!\n", name.str());

	return success;
}
Esempio n. 3
0
void FileViewer::ShowReference(const wxString& ref)
{
    const wxFileName filename = GetFilename(ref);
    wxFFile file;
    wxString data;

    if ( !filename.IsFileReadable() ||
         !file.Open(filename.GetFullPath()) ||
         !file.ReadAll(&data, wxConvAuto()) )
    {
        wxLogError(_("Error opening file %s!"), filename.GetFullPath().c_str());
        return;
    }

    m_current = ref;

    // support GNOME's xml2po's extension to references in the form of
    // filename:line(xml_node):
    wxString linenumStr = ref.AfterLast(_T(':')).BeforeFirst(_T('('));

    long linenum;
    if (!linenumStr.ToLong(&linenum))
        linenum = 0;

    m_text->SetReadOnly(false);
    m_text->SetValue(data);
    m_text->SetReadOnly(true);

    m_text->MarkerDeleteAll(1);
    m_text->MarkerAdd((int)linenum - 1, 1);

    // Center the highlighted line:
    int lineHeight = m_text->TextHeight((int)linenum);
    int linesInWnd = m_text->GetSize().y / lineHeight;
    m_text->ScrollToLine(wxMax(0, (int)linenum - linesInWnd/2));

}
Esempio n. 4
0
void CFLTKEditor::Close()
{
	if (!CheckSave())
		return;

	if (m_iCurEditorID < 0 || m_iCurEditorID >= int(m_mEditorData.Count()) )
		return;

	DeleteEditor(m_iCurEditorID);

	if (m_iCurEditorID > 0)
	{
		m_iCurEditorID--;
		SetCurEditor(m_iCurEditorID);
	}
	else if (m_iCurEditorID >= int(m_mEditorData.Count()))
	{
		char pcName[100];

		NewEditor();
		m_iCurEditorID = 0;
		SetCurEditor(m_iCurEditorID);

		GetFilename() = "";
		sprintf(pcName, "Untitled %d", sm_iNewFileNo++);
		GetName() = pcName;
		GetPath() = "./";
		GetTextBuffer()->select(0, GetTextBuffer()->length());
		GetTextBuffer()->remove_selection();
		IsFileChanged() = false;
		GetTextBuffer()->call_modify_callbacks();

		SetTitle();
	}

	UpdateFileList();
}
Esempio n. 5
0
bool GenPlugin::Unload()
{
	if( !IsLoaded() ) return true;

	TCHAR szBuffer[ 5000 ];
	_stprintf( szBuffer, TEXT( "Unloading <%s>" ), GetFilename() );
	Console::Append( szBuffer );
	Console::Append( TEXT( " " ) );


	// Quit
	if( plugin )
	{
		if( plugin->quit ) plugin->quit();
		plugin = NULL;
	}


	// Remove wndproc hook
	if( ( iHookerIndex != -1 ) && ( iHookerIndex == iWndprocHookCounter - 1 ) )
	{
		// If we don't restore it the plugins wndproc will
		// still be called which is not there anymore -> crash
		SetWindowLong( WindowMain, GWL_WNDPROC, ( LONG )WndprocBackup );
		Console::Append( TEXT( "Wndproc hook removed (by host)" ) );
		Console::Append( TEXT( " " ) );

		iHookerIndex  = -1;
		iWndprocHookCounter--;
	}


	FreeLibrary( hDLL );
	hDLL = NULL;

	return true;
}
Esempio n. 6
0
//-----------------------------------------------------------------------------
// The script class constructor.
//-----------------------------------------------------------------------------
Script::Script( char *name, char *path ) : Resource< Script >( name, path )
{
	// Create the linked list that will store all of the script's variables.
	m_variables = new LinkedList< Variable >;

	// Open the script file using the filename.
	FILE *file = NULL;
	if( ( file = fopen( GetFilename(), "r" ) ) == NULL )
		return;

	// Continue reading from the file until the eof is reached.
	bool read = false;
	char buffer[MAX_PATH];
	fscanf( file, "%s", buffer );
	while( feof( file ) == 0 )
	{
		// Check if the file position indicator is between a #begin and #end
		// statement. If so then read the data into the variable linked list.
		if( read == true )
		{
			// Stop reading data if an #end statement has been reached.
			if( strcmp( buffer, "#end" ) == 0 )
				read = false;
			else
				m_variables->Add( new Variable( buffer, file ) );
		}
		else if( strcmp( buffer, "#begin" ) == 0 )
			read = true;

		// Read the next string.
		fscanf( file, "%s", buffer );
	}

	// Close the script file.
	fclose( file );
}
Esempio n. 7
0
std::shared_ptr<const sf::Image> ResourceManager::GetImage( const std::string& path ) {
	auto image_iter = m_images.find( path );

	if( image_iter != m_images.end() ) {
		return image_iter->second;
	}

	// Try to load.
	auto loader = GetMatchingLoader( path );

	if( !loader ) {
		return std::shared_ptr<const sf::Image>();
	}

	auto image = loader->LoadImage( GetFilename( path, *loader ) );

	if( !image ) {
		return std::shared_ptr<const sf::Image>();
	}

	// Cache.
	m_images[path] = image;
	return image;
}
Esempio n. 8
0
//-----------------------------------------------------------------------------
// Saves the script to file.
//-----------------------------------------------------------------------------
void Script::SaveScript( char *filename )
{
	FILE *file = NULL;
	char output[MAX_PATH];

	// Open the given filename if available, otherwise the internal filename.
	if( filename != NULL )
	{
		if( ( file = fopen( filename, "w" ) ) == NULL )
			return;
	}
	else
	{
		if( ( file = fopen( GetFilename(), "w" ) ) == NULL )
			return;
	}

	// Write the #begin statement to the file.
	fputs( "#begin\n", file );

	// Write each variable to the file.
	m_variables->Iterate( true );
	while( m_variables->Iterate() != NULL )
	{
		switch( m_variables->GetCurrent()->GetType() )
		{
			case VARIABLE_BOOL:
				if( *((bool*)m_variables->GetCurrent()->GetData()) == true )
					sprintf( output, "%s bool true", m_variables->GetCurrent()->GetName() );
				else
					sprintf( output, "%s bool false", m_variables->GetCurrent()->GetName() );
				fputs( output, file );
				fputs( "\n", file );
				continue;

			case VARIABLE_COLOUR:
				sprintf( output, "%s colour %f %f %f %f", m_variables->GetCurrent()->GetName(), ( (D3DCOLORVALUE*)m_variables->GetCurrent()->GetData() )->r, ( (D3DCOLORVALUE*)m_variables->GetCurrent()->GetData() )->g, ( (D3DCOLORVALUE*)m_variables->GetCurrent()->GetData() )->b, ( (D3DCOLORVALUE*)m_variables->GetCurrent()->GetData() )->a );
				fputs( output, file );
				fputs( "\n", file );
				continue;

			case VARIABLE_FLOAT:
				sprintf( output, "%s float %f", m_variables->GetCurrent()->GetName(), *(float*)m_variables->GetCurrent()->GetData() );
				fputs( output, file );
				fputs( "\n", file );
				continue;

			case VARIABLE_NUMBER:
				sprintf( output, "%s number %d", m_variables->GetCurrent()->GetName(), *(long*)m_variables->GetCurrent()->GetData() );
				fputs( output, file );
				fputs( "\n", file );
				continue;

			case VARIABLE_STRING:
				sprintf( output, "%s string \"%s\"", m_variables->GetCurrent()->GetName(), (char*)m_variables->GetCurrent()->GetData() );
				fputs( output, file );
				fputs( "\n", file );
				continue;

			case VARIABLE_VECTOR:
				sprintf( output, "%s vector %f %f %f", m_variables->GetCurrent()->GetName(), ( (D3DXVECTOR3*)m_variables->GetCurrent()->GetData() )->x, ( (D3DXVECTOR3*)m_variables->GetCurrent()->GetData() )->y, ( (D3DXVECTOR3*)m_variables->GetCurrent()->GetData() )->z );
				fputs( output, file );
				fputs( "\n", file );
				continue;

			default:
				sprintf( output, "%s unknown %s", m_variables->GetCurrent()->GetName(), (char*)m_variables->GetCurrent()->GetData() );
				fputs( output, file );
				fputs( "\n", file );
				continue;
		}
	}

	// Write the #end statement to the file.
	fputs( "#end", file );

	// Close the script file.
	fclose( file );
}
Esempio n. 9
0
QString HTTPLiveStream::GetCurrentFilename(bool audioOnly, bool encoded) const
{
    return GetFilename(m_curSegment, false, audioOnly, encoded);
}
Esempio n. 10
0
StreamSample::StreamSample ( const String* filename, TSample type ) : BaseSample( filename, type )
{
    m_playing = false;
    String c = *GetFilename();
}
Esempio n. 11
0
//-----------------------------------------------------------------------------
// The mesh class constructor.
//-----------------------------------------------------------------------------
Mesh::Mesh( char *name, char *path ) : Resource< Mesh >( name, path )
{
	// Create the list of reference points.
	m_frames = new LinkedList< Frame >;
	m_refPoints = new LinkedList< Frame >;

	// Load the mesh's frame hierarchy.
	AllocateHierarchy ah;
	D3DXLoadMeshHierarchyFromX( GetFilename(), D3DXMESH_MANAGED, Engine::GetInstance()->GetDevice(), &ah, NULL, (D3DXFRAME**)&m_firstFrame, &m_animationController );

	// Disable all the animation tracks initially.
	if( m_animationController != NULL )
		for( unsigned long t = 0; t < m_animationController->GetMaxNumTracks(); ++t )
			m_animationController->SetTrackEnable( t, false );

	// Invalidate the bone transformation matrices array.
	m_boneMatrices = NULL;
	m_totalBoneMatrices = 0;

	// Prepare the frame hierarchy.
	PrepareFrame( m_firstFrame );

	// Allocate memory for the bone matrices.
	m_boneMatrices = new D3DXMATRIX[m_totalBoneMatrices];

	// Create a static (non-animated) version of the mesh.
	m_staticMesh = new MeshContainer;
	ZeroMemory( m_staticMesh, sizeof( MeshContainer ) );

	// Load the mesh.
	ID3DXBuffer *materialBuffer, *adjacencyBuffer;
	D3DXLoadMeshFromX( GetFilename(), D3DXMESH_MANAGED, Engine::GetInstance()->GetDevice(), &adjacencyBuffer, &materialBuffer, NULL, &m_staticMesh->NumMaterials, &m_staticMesh->originalMesh );

	// Optimise the mesh for better rendering performance.
	m_staticMesh->originalMesh->OptimizeInplace( D3DXMESHOPT_COMPACT | D3DXMESHOPT_ATTRSORT | D3DXMESHOPT_VERTEXCACHE, (DWORD*)adjacencyBuffer->GetBufferPointer(), NULL, NULL, NULL );

	// Finished with the adjacency buffer, so destroy it.
	SAFE_RELEASE( adjacencyBuffer );

	// Check if the mesh has any materials.
	if( m_staticMesh->NumMaterials > 0 )
	{
		// Create the array of materials.
		m_staticMesh->materials = new Material*[m_staticMesh->NumMaterials];

		// Get the list of materials from the material buffer.
		D3DXMATERIAL *materials = (D3DXMATERIAL*)materialBuffer->GetBufferPointer();

		// Load each material into the array via the material manager.
		for( unsigned long m = 0; m < m_staticMesh->NumMaterials; m++ )
		{
			// Ensure the material has a texture.
			if( materials[m].pTextureFilename )
			{
				// Get the name of the material's script and load it.
				char *name = new char[strlen( materials[m].pTextureFilename ) + 5];
				sprintf( name, "%s.txt", materials[m].pTextureFilename );
				m_staticMesh->materials[m] = Engine::GetInstance()->GetMaterialManager()->Add( name, GetPath() );
				SAFE_DELETE_ARRAY( name );
			}
			else
				m_staticMesh->materials[m] = NULL;
		}
	}

	// Create the bounding volume around the mesh.
	BoundingVolumeFromMesh( m_staticMesh->originalMesh );

	// Destroy the material buffer.
	SAFE_RELEASE( materialBuffer );

	// Create a vertex array and an array of indices into the vertex array.
	m_vertices = new Vertex[m_staticMesh->originalMesh->GetNumVertices()];
	m_indices = new unsigned short[m_staticMesh->originalMesh->GetNumFaces() * 3];

	// Use the arrays to store a local copy of the static mesh's vertices and
	// indices so that they can be used by the scene manager on the fly.
	Vertex* verticesPtr;
	m_staticMesh->originalMesh->LockVertexBuffer( 0, (void**)&verticesPtr );
	unsigned short *indicesPtr;
	m_staticMesh->originalMesh->LockIndexBuffer( 0, (void**)&indicesPtr );

	memcpy( m_vertices, verticesPtr, VERTEX_FVF_SIZE * m_staticMesh->originalMesh->GetNumVertices() );
	memcpy( m_indices, indicesPtr, sizeof( unsigned short ) * m_staticMesh->originalMesh->GetNumFaces() * 3 );

	m_staticMesh->originalMesh->UnlockVertexBuffer();
	m_staticMesh->originalMesh->UnlockIndexBuffer();
}
Esempio n. 12
0
bool C4MusicSystem::Play(const char *szSongname, bool fLoop, int fadetime_ms, double max_resume_time, bool allow_break)
{
	// pause is done
	is_waiting = false;
	upcoming_music_file = NULL;

	// music off?
	if (Game.IsRunning ? !Config.Sound.RXMusic : !Config.Sound.FEMusic)
		return false;

	// info
	if (::Config.Sound.Verbose)
	{
		LogF("MusicSystem: Play(\"%s\", %s, %d, %.3lf, %s)", szSongname ? szSongname : "(null)", fLoop ? "true" : "false", fadetime_ms, max_resume_time, allow_break ? "true" : "false");
	}

	C4MusicFile* NewFile = NULL;

	// Specified song name
	if (szSongname && szSongname[0])
	{
		// Search in list
		for (NewFile = Songs; NewFile; NewFile = NewFile->pNext)
		{
			char songname[_MAX_FNAME + 1];
			SCopy(szSongname, songname); DefaultExtension(songname, "mid");
			if (SEqual(GetFilename(NewFile->FileName), songname))
				break;
			SCopy(szSongname, songname); DefaultExtension(songname, "ogg");
			if (SEqual(GetFilename(NewFile->FileName), songname))
				break;
		}
	}
	else
	{
		// When resuming, prefer songs that were interrupted before
		if (max_resume_time > 0)
		{
			C4TimeMilliseconds t_now = C4TimeMilliseconds::Now();
			for (C4MusicFile *check_file = Songs; check_file; check_file = check_file->pNext)
				if (!check_file->NoPlay)
				{
					if (check_file->HasResumePos() && check_file->GetRemainingTime() > max_resume_time)
						if (!music_max_position_memory || (t_now - check_file->GetLastInterruptionTime() <= music_max_position_memory*1000))
							if (!NewFile || NewFile->LastPlayed < check_file->LastPlayed)
								NewFile = check_file;
				}
		}

		// Random song
		if (!NewFile)
		{
			// Intead of a new song, is a break also allowed?
			if (allow_break) ScheduleWaitTime();
			if (!is_waiting)
			{
				if (::Config.Sound.Verbose) LogF("  ASongCount=%d SCounter=%d", ASongCount, SCounter);
				// try to find random song
				int32_t new_file_playability = 0, new_file_num_rolls = 0;
				for (C4MusicFile *check_file = Songs; check_file; check_file = check_file->pNext)
				{
					if (!check_file->NoPlay)
					{
						// Categorize song playability:
						// 0 = no song found yet
						// 1 = song was played recently
						// 2 = song not played recently
						// 3 = song was not played yet
						int32_t check_file_playability = (check_file->LastPlayed < 0) ? 3 : (SCounter - check_file->LastPlayed <= ASongCount / 2) ? 1 : 2;
						if (::Config.Sound.Verbose) LogF("  Song LastPlayed %d [%d] (%s)", int(check_file->LastPlayed), int(check_file_playability), check_file->GetDebugInfo().getData());
						if (check_file_playability > new_file_playability)
						{
							// Found much better fit. Play this and reset number of songs found in same plyability
							new_file_num_rolls = 1;
							NewFile = check_file;
							new_file_playability = check_file_playability;
						}
						else if (check_file_playability == new_file_playability)
						{
							// Found a fit in the same playability category: Roll for it
							if (!SafeRandom(++new_file_num_rolls)) NewFile = check_file;
						}
						else
						{
							// Worse playability - ignore this song
						}
					}
				}
			}

		}
	}

	// File (or wait time) found?
	if (!NewFile && !is_waiting)
		return false;

	// Stop/Fade out old music
	bool is_fading = (fadetime_ms && NewFile != PlayMusicFile && PlayMusicFile);
	if (!is_fading)
	{
		Stop();
	}
	else
	{
		C4TimeMilliseconds tNow = C4TimeMilliseconds::Now();
		if (FadeMusicFile)
		{
			if (FadeMusicFile == NewFile && FadeMusicFile->IsLooping() == fLoop && tNow < FadeTimeEnd)
			{
				// Fading back to a song while it wasn't fully faded out yet. Just swap our pointers and fix timings for that.
				FadeMusicFile = PlayMusicFile;
				PlayMusicFile = NewFile;
				FadeTimeEnd = tNow + fadetime_ms * (tNow - FadeTimeStart) / (FadeTimeEnd - FadeTimeStart);
				FadeTimeStart = FadeTimeEnd - fadetime_ms;
				return true;
			}
			else
			{
				// Fading to a third song while the previous wasn't faded out yet
				// That's pretty chaotic anyway, so just cancel the last song
				// Also happens if fading should already be done, in which case it won't harm to stop now
				// (It would stop on next call to Execute() anyway)
				// Also happens when fading back to the same song but loop status changes, but that should be really uncommon.
				FadeMusicFile->Stop();
			}

		}
		FadeMusicFile = PlayMusicFile;
		PlayMusicFile = NULL;
		FadeTimeStart = tNow;
		FadeTimeEnd = FadeTimeStart + fadetime_ms;
	}

	// Waiting?
	if (!NewFile) return false;

	// If the old file is being faded out and a new file would just start, start delayed and without fading
	// so the beginning of a song isn't faded unnecesserily (because our songs often start very abruptly)
	if (is_fading && (!NewFile->HasResumePos() || NewFile->GetRemainingTime() <= max_resume_time))
	{
		upcoming_music_file = NewFile;
		is_waiting = true;
		wait_time_end = FadeTimeEnd;
		return false;
	}

	if (!Play(NewFile, fLoop, max_resume_time)) return false;

	if (is_fading) PlayMusicFile->SetVolume(0);

	return true;
}
Esempio n. 13
0
	void INI_SaveSettings()
	{
		regini::regini_file inifile;
		inifile.open(GetFilename());

		inifile.write("General", "INIversion", INIversion);
		inifile.write("General", "ProcPriority", bPriority ? 1 : 0);
		inifile.write("General", "KeepAwake", bKeepAwake ? 1 : 0);
		inifile.write("General", "SwapPorts", SwapPortsEnabled ? 1 : 0);
		inifile.write("General", "Multitap", multitap);

		for(s32 port = 0; port < 4; port++)
		{
			std::string section = "Controller" + std::to_string(port);
			_Settings &set = settings[port];

			s32 AxisInverted = *(s32*)set.axisInverted;
			s32 AxisRemap = *(s32*)set.axisRemap;

			inifile.write(section, "AxisInverted", AxisInverted);
			inifile.write(section, "AxisRemap", AxisRemap);

			inifile.write(section, "TriggerDeadzone", set.triggerDeadzone);
			inifile.write(section, "Pressure", set.pressureRate);
			inifile.write(section, "Rumble", set.rumble);
			inifile.write(section, "SticksLocked", set.sticksLocked ? 1 : 0);

			inifile.write(section, "XInputPort", set.xinputPort);
			inifile.write(section, "Disabled", set.disabled ? 1 : 0);
			inifile.write(section, "DefautMode", set.defaultAnalog ? 1 : 0);
			inifile.write(section, "GreenAnalog", set.greenAnalog ? 1 : 0);
			inifile.write(section, "GuitarController", set.isGuitar ? 1 : 0);

			inifile.write(section, "SwapDCBumpers", set.SwapDCBumpers ? 1 : 0);
			inifile.write(section, "SwapSticks", set.SwapSticksEnabled ? 1 : 0);
			inifile.write(section, "SwapXO", set.SwapXO ? 1 : 0);

			// Left Stick Settings

			inifile.write(section, "LS_4wayDAC", set.stickL.b4wayDAC ? 1 : 0);
			inifile.write(section, "LS_EnableDAC", set.stickL.DACenabled ? 1 : 0);
			inifile.write(section, "LS_DACthreshold", set.stickL.DACthreshold);

			inifile.write(section, "LS_ExtentionThreshold", set.stickL.extThreshold);

			inifile.write(section, "LS_Linearity", set.stickL.linearity);
			inifile.write(section, "LS_AntiDeadzone", set.stickL.antiDeadzone);
			inifile.write(section, "LS_Deadzone", set.stickL.deadzone);

			// Right Stick Settings

			inifile.write(section, "RS_4wayDAC", set.stickR.b4wayDAC ? 1 : 0);
			inifile.write(section, "RS_EnableDAC", set.stickR.DACenabled ? 1 : 0);
			inifile.write(section, "RS_DACthreshold", set.stickR.DACthreshold);

			inifile.write(section, "RS_ExtentionThreshold", set.stickR.extThreshold);

			inifile.write(section, "RS_Linearity", set.stickR.linearity);
			inifile.write(section, "RS_AntiDeadzone", set.stickR.antiDeadzone);
			inifile.write(section, "RS_Deadzone", set.stickR.deadzone);
		}

		inifile.save();
	}
Esempio n. 14
0
	void INI_LoadSettings()
	{
		settings[0].xinputPort = 0;
		settings[1].xinputPort = 1;
		settings[2].xinputPort = 2;
		settings[3].xinputPort = 3;

		regini::regini_file inifile;
		inifile.open(GetFilename());

		if (inifile.read("General", "INIversion", -1) != INIversion)
		{
			return;
		}

		bPriority = inifile.read("General", "ProcPriority", 0) == 1;
		SetPriority();
			
		SwapPortsEnabled = inifile.read("General", "SwapPorts", 0) == 1;
		bKeepAwake       = inifile.read("General", "KeepAwake", 0) == 1;
		multitap         = inifile.read("General", "Multitap", 0) & 0xF;
		multitap = multitap > 2 ? 0 : multitap;

		for (s32 port = 0; port < 4; port++)
		{
			std::string section = "Controller" + std::to_string(port);
			_Settings &set = settings[port];
			s32 result;

			result = inifile.read(section, "AxisInverted", -1);
			if (result != -1)  *(s32*)set.axisInverted = result;

			result = inifile.read(section, "AxisRemap", -1);
			if (result != -1) *(s32*)set.axisRemap = result;

			set.triggerDeadzone = inifile.read(section, "TriggerDeadzone", set.triggerDeadzone) & 0xFF;
			set.pressureRate    = inifile.read(section, "Pressure", set.pressureRate) & 0xFF;
			set.rumble          = inifile.read(section, "Rumble", set.rumble);
			set.xinputPort      = inifile.read(section, "XInputPort", set.xinputPort) & 0xF;

			set.disabled      = !!inifile.read(section, "Disabled", 0);
			set.sticksLocked  = !!inifile.read(section, "SticksLocked", 1);
			set.defaultAnalog = !!inifile.read(section, "DefautMode", 1);

			set.greenAnalog       = !!inifile.read(section, "GreenAnalog", 0);
			set.isGuitar          = !!inifile.read(section, "GuitarController", 0);
			set.SwapDCBumpers     = !!inifile.read(section, "SwapDCBumpers", 0);
			set.SwapSticksEnabled = !!inifile.read(section, "SwapSticks", 0);
			set.SwapXO            = !!inifile.read(section, "SwapXO", 0);

			// Left Stick Settings

			set.stickL.b4wayDAC   = !!inifile.read(section, "LS_4wayDAC", 0);
			set.stickL.DACenabled = !!inifile.read(section, "LS_EnableDAC", 0);

			set.stickL.DACthreshold = inifile.read(section, "LS_DACthreshold", set.stickL.DACthreshold);
			set.stickL.extThreshold = inifile.read(section, "LS_ExtentionThreshold", set.stickL.extThreshold);
			set.stickL.extMult = 46339.535798279205464084934426179 / set.stickL.extThreshold;

			set.stickL.linearity    = inifile.read(section, "LS_Linearity", set.stickL.linearity);
			set.stickL.antiDeadzone = inifile.read(section, "LS_AntiDeadzone", set.stickL.antiDeadzone);
			set.stickL.deadzone     = inifile.read(section, "LS_Deadzone", set.stickL.deadzone);

			// Right Stick Settings

			set.stickR.b4wayDAC   = !!inifile.read(section, "RS_4wayDAC", 0);
			set.stickR.DACenabled = !!inifile.read(section, "RS_EnableDAC", 0);

			set.stickR.DACthreshold = inifile.read(section, "RS_DACthreshold", set.stickR.DACthreshold);
			set.stickR.extThreshold = inifile.read(section, "RS_ExtentionThreshold", set.stickR.extThreshold);
			set.stickR.extMult = 46339.535798279205464084934426179 / set.stickR.extThreshold;

			set.stickR.linearity    = inifile.read(section, "RS_Linearity", set.stickR.linearity);
			set.stickR.antiDeadzone = inifile.read(section, "RS_AntiDeadzone", set.stickR.antiDeadzone);
			set.stickR.deadzone     = inifile.read(section, "RS_Deadzone", set.stickR.deadzone);
		}

	}
Esempio n. 15
0
void CModelConverter::SaveSIA(const tstring& sFilename)
{
	tstring sSIAFileName = tstring(GetDirectory(sFilename).c_str()) + _T("/") + GetFilename(sFilename).c_str() + _T(".sia");

	std::wofstream sFile(convertstring<tchar, char>(sSIAFileName).c_str());
	if (!sFile.is_open())
		return;

	sFile.precision(8);
	sFile.setf(std::ios::fixed, std::ios::floatfield);

	if (m_pWorkListener)
	{
		m_pWorkListener->BeginProgress();
		m_pWorkListener->SetAction(_T("Writing materials..."), 0);
	}

	sFile << _T("-Version 1.0") << std::endl;

	for (size_t i = 0; i < m_pScene->GetNumMaterials(); i++)
	{
		sFile << _T("-Mat") << std::endl;

		CConversionMaterial* pMaterial = m_pScene->GetMaterial(i);

		sFile << "-amb " << pMaterial->m_vecAmbient.x << _T(" ") << pMaterial->m_vecAmbient.y << _T(" ") << pMaterial->m_vecAmbient.z << _T(" 0") << std::endl;
		sFile << "-dif " << pMaterial->m_vecDiffuse.x << _T(" ") << pMaterial->m_vecDiffuse.y << _T(" ") << pMaterial->m_vecDiffuse.z << _T(" 0") << std::endl;
		sFile << "-spec " << pMaterial->m_vecSpecular.x << _T(" ") << pMaterial->m_vecSpecular.y << _T(" ") << pMaterial->m_vecSpecular.z << _T(" 0") << std::endl;
		sFile << "-emis " << pMaterial->m_vecEmissive.x << _T(" ") << pMaterial->m_vecEmissive.y << _T(" ") << pMaterial->m_vecEmissive.z << _T(" 0") << std::endl;
		sFile << "-shin " << pMaterial->m_flShininess << std::endl;
		sFile << "-name \"" << pMaterial->GetName().c_str() << _T("\"") << std::endl;
		if (pMaterial->GetDiffuseTexture().length() > 0)
			sFile << "-tex \"" << pMaterial->GetDiffuseTexture().c_str() << _T("\"") << std::endl;
		sFile << _T("-endMat") << std::endl;
	}

	for (size_t i = 0; i < m_pScene->GetNumMeshes(); i++)
	{
		CConversionMesh* pMesh = m_pScene->GetMesh(i);

		size_t iAddV = pMesh->GetNumVertices();
		size_t iAddE = pMesh->GetNumEdges();
		size_t iAddUV = pMesh->GetNumUVs();
		size_t iAddN = pMesh->GetNumNormals();

		// Find the default scene for this mesh.
		CConversionSceneNode* pScene = NULL;
		for (size_t j = 0; j < m_pScene->GetNumScenes(); j++)
		{
			if (m_pScene->GetScene(j)->GetName() == pMesh->GetName() + _T(".sia"))
			{
				pScene = m_pScene->GetScene(j);
				break;
			}
		}

		tstring sNodeName = pMesh->GetName();

		sFile << _T("-Shape") << std::endl;
		sFile << _T("-snam \"") << sNodeName.c_str() << _T("\"") << std::endl;
		sFile << _T("-shad 0") << std::endl;
		sFile << _T("-shadw 1") << std::endl;

		if (m_pWorkListener)
			m_pWorkListener->SetAction((tstring(_T("Writing ")) + sNodeName + _T(" vertices...")).c_str(), pMesh->GetNumVertices());

		for (size_t iVertices = 0; iVertices < pMesh->GetNumVertices(); iVertices++)
		{
			if (m_pWorkListener)
				m_pWorkListener->WorkProgress(iVertices);

			Vector vecVertex = pMesh->GetVertex(iVertices);
			sFile << _T("-vert ") << vecVertex.x << _T(" ") << vecVertex.y << _T(" ") << vecVertex.z << std::endl;
		}

		if (m_pWorkListener)
			m_pWorkListener->SetAction((tstring(_T("Writing ")) + sNodeName + _T(" edges...")).c_str(), pMesh->GetNumEdges());

		tstring sCreases;

		for (size_t iEdges = 0; iEdges < pMesh->GetNumEdges(); iEdges++)
		{
			if (m_pWorkListener)
				m_pWorkListener->WorkProgress(iEdges);

			CConversionEdge* pEdge = pMesh->GetEdge(iEdges);
			sFile << _T("-edge ") << pEdge->v1 << _T(" ") << pEdge->v2 << std::endl;

			if (pEdge->m_bCreased)
				sCreases += sprintf(tstring(" %d"), iEdges);
		}

		if (sCreases.length())
			sFile << _T("-creas") << sCreases.c_str() << std::endl;

		if (m_pWorkListener)
			m_pWorkListener->SetAction((tstring(_T("Writing ")) + sNodeName + _T(" faces...")).c_str(), pMesh->GetNumFaces());

		size_t iMaterial = 0;

		for (size_t iFaces = 0; iFaces < pMesh->GetNumFaces(); iFaces++)
		{
			if (m_pWorkListener)
				m_pWorkListener->WorkProgress(iFaces);

			CConversionFace* pFace = pMesh->GetFace(iFaces);

			if (iFaces == 0 || iMaterial != pFace->m)
			{
				iMaterial = pFace->m;

				if (iMaterial == ~0)
					sFile << _T("-setmat -1") << std::endl;
				else
				{
					CConversionSceneNode* pNode = m_pScene->GetDefaultSceneMeshInstance(pScene, pMesh, false);

					if (!pNode || pNode->GetNumMeshInstances() != 1)
						sFile << _T("-setmat -1") << std::endl;
					else
					{
						CConversionMaterialMap* pMap = pNode->GetMeshInstance(0)->GetMappedMaterial(iMaterial);
						if (pMap)
							sFile << _T("-setmat -1") << std::endl;
						else
							sFile << _T("-setmat ") << pMap->m_iMaterial << std::endl;
					}
				}
			}

			sFile << _T("-face ") << pFace->GetNumVertices();

			TAssert(pFace->GetNumEdges() == pFace->GetNumVertices());

			for (size_t iVertsInFace = 0; iVertsInFace < pFace->GetNumVertices(); iVertsInFace++)
			{
				CConversionVertex* pVertex = pFace->GetVertex(iVertsInFace);
				CConversionVertex* pNextVertex = pFace->GetVertex((iVertsInFace+1)%pFace->GetNumVertices());

				// Find the edge that heads in a counter-clockwise direction.
				size_t iEdge = ~0;
				for (size_t i = 0; i < pFace->GetNumEdges(); i++)
				{
					size_t iEdgeCandidate = pFace->GetEdge(i);
					CConversionEdge* pEdge = pMesh->GetEdge(iEdgeCandidate);
					if ((pEdge->v1 == pVertex->v && pEdge->v2 == pNextVertex->v) || (pEdge->v2 == pVertex->v && pEdge->v1 == pNextVertex->v))
					{
						iEdge = iEdgeCandidate;
						break;
					}
				}
				TAssert(iEdge != ~0);

				Vector vecUV = pMesh->GetUV(pVertex->vu);
				sFile << _T(" ") << pVertex->v << _T(" ") << iEdge << _T(" ") << vecUV.x << _T(" ") << vecUV.y;
			}

			sFile << std::endl;
		}

		sFile << _T("-axis 0 0.5 0 1 0 0 0 1 0 0 0 1") << std::endl;
		sFile << _T("-mirp 0 0 0 1 0 0") << std::endl;
		sFile << _T("-endShape") << std::endl;
	}

	if (m_pWorkListener)
		m_pWorkListener->EndProgress();
}
Esempio n. 16
0
// Silo ascii
void CModelConverter::ReadSIA(const tstring& sFilename)
{
	if (m_pWorkListener)
		m_pWorkListener->BeginProgress();

	CConversionSceneNode* pScene = m_pScene->GetScene(m_pScene->AddScene(GetFilename(sFilename).append(_T(".sia"))));

	if (m_pWorkListener)
		m_pWorkListener->SetAction(_T("Reading file into memory..."), 0);

	FILE* fp = tfopen(sFilename, _T("r"));

	if (!fp)
	{
		printf("No input file. Sorry!\n");
		return;
	}

	fseek(fp, 0L, SEEK_END);
	long iOBJSize = ftell(fp);
	fseek(fp, 0L, SEEK_SET);

	// Make sure we allocate more than we need just in case.
	size_t iFileSize = (iOBJSize+1) * (sizeof(tchar)+1);
	tchar* pszEntireFile = (tchar*)malloc(iFileSize);
	tchar* pszCurrent = pszEntireFile;

	// Read the entire file into an array first for faster processing.
	tstring sLine;
	while (fgetts(sLine, fp))
	{
		tstrncpy(pszCurrent, iFileSize-(pszCurrent-pszEntireFile), sLine.c_str(), sLine.length());
		size_t iLength = sLine.length();

		if (pszCurrent[iLength-1] == _T('\n'))
		{
			pszCurrent[iLength-1] = _T('\0');
			iLength--;
		}

		pszCurrent += iLength;
		pszCurrent++;

		if (m_pWorkListener)
			m_pWorkListener->WorkProgress(0);
	}

	pszCurrent[0] = _T('\0');

	fclose(fp);

	const tchar* pszLine = pszEntireFile;
	const tchar* pszNextLine = NULL;
	while (pszLine < pszCurrent)
	{
		if (pszNextLine)
			pszLine = pszNextLine;

		pszNextLine = pszLine + tstrlen(pszLine) + 1;

		// This code used to call StripWhitespace() but that's too slow for very large files w/ millions of lines.
		// Instead we'll just cut the whitespace off the front and deal with whitespace on the end when we come to it.
		while (*pszLine && IsWhitespace(*pszLine))
			pszLine++;

		if (tstrlen(pszLine) == 0)
			continue;

		eastl::vector<tstring> aTokens;
		tstrtok(pszLine, aTokens, _T(" "));
		const tchar* pszToken = aTokens[0].c_str();

		if (tstrncmp(pszToken, _T("-Version"), 8) == 0)
		{
			// Warning if version is later than 1.0, we may not support it
			int iMajor, iMinor;
			eastl::vector<tstring> asTokens;
			tstrtok(pszLine, asTokens, _T(" ."));

			if (asTokens.size() >= 3)
			{
				iMajor = stoi(asTokens[1]);
				iMinor = stoi(asTokens[2]);
				if (iMajor != 1 && iMinor != 0)
					printf("WARNING: I was programmed for version 1.0, this file is version %d.%d, so this might not work exactly right!\n", iMajor, iMinor);
			}
		}
		else if (tstrncmp(pszToken, _T("-Mat"), 4) == 0)
		{
			pszNextLine = ReadSIAMat(pszNextLine, pszCurrent, pScene, sFilename);
		}
		else if (tstrncmp(pszToken, _T("-Shape"), 6) == 0)
		{
			pszNextLine = ReadSIAShape(pszNextLine, pszCurrent, pScene);
		}
		else if (tstrncmp(pszToken, _T("-Texshape"), 9) == 0)
		{
			// This is the 3d UV space of the object, but we only care about its 2d UV space which is contained in rhw -Shape section, so meh.
			pszNextLine = ReadSIAShape(pszNextLine, pszCurrent, pScene, false);
		}
	}

	free(pszEntireFile);

	m_pScene->SetWorkListener(m_pWorkListener);

	for (size_t i = 0; i < m_pScene->GetNumMeshes(); i++)
	{
		m_pScene->GetMesh(i)->CalculateEdgeData();
		m_pScene->GetMesh(i)->CalculateVertexNormals();
		m_pScene->GetMesh(i)->CalculateVertexTangents();
	}

	m_pScene->CalculateExtends();

	if (m_pWorkListener)
		m_pWorkListener->EndProgress();
}
Esempio n. 17
0
FileList::FileList(const String & filepath)
{
	path = FileSystem::Instance()->SystemPathForFrameworkPath(filepath);

// Windows version
#if defined(__DAVAENGINE_WIN32__)

	//char tmp[_MAX_PATH];
	//_getcwd(tmp, _MAX_PATH);
	//Path = tmp;
	String prevDir = FileSystem::Instance()->GetCurrentWorkingDirectory();
	BOOL res = SetCurrentDirectoryA(path.c_str());

	if (res)
	{
		struct _finddata_t c_file;
		intptr_t hFile;
		FileEntry entry;

		if( (hFile = _findfirst( "*", &c_file )) != -1L )
		{
			do
			{
				entry.name = c_file.name;
				entry.size = c_file.size;
				entry.isDirectory = (_A_SUBDIR & c_file.attrib) != 0;
				fileList.push_back(entry);
				//Logger::Debug("filelist: %s %s", filepath.c_str(), entry.name.c_str());
			}
			while( _findnext( hFile, &c_file ) == 0 );

			_findclose( hFile );
		}
	}
	FileSystem::Instance()->SetCurrentWorkingDirectory(prevDir);

	//TODO add drives
	//entry.Name = "E:\\";
	//entry.isDirectory = true;
	//Files.push_back(entry);
#elif defined(__DAVAENGINE_MACOS__) || defined(__DAVAENGINE_IPHONE__) || defined (__DAVAENGINE_ANDROID__)
	struct dirent **namelist;
	FileEntry entry;

#if defined (__DAVAENGINE_ANDROID__)
	int32 n = scandir(path.c_str(), &namelist, 0, alphasortAndroid);
#else //#if defined (__DAVAENGINE_ANDROID__)
	int32 n = scandir(path.c_str(), &namelist, 0, alphasort);
#endif //#if defined (__DAVAENGINE_ANDROID__)    
    
	if (n >= 0)
	{
		while(n--)
		{
			entry.name = namelist[n]->d_name;
			entry.size = 0;
			entry.isDirectory = namelist[n]->d_type == DT_DIR;
			fileList.push_back(entry);
			free(namelist[n]);
		}
		free(namelist);
	}
#endif //PLATFORMS

	directoryCount = 0;
	fileCount = 0;
	for (int fi = 0; fi < GetCount(); ++fi)
	{
		if (IsDirectory(fi))
		{
			String filename = GetFilename(fi);
			if ((filename != ".") && (filename != ".."))
				directoryCount++;
		}else
			fileCount++;
	}
}
Esempio n. 18
0
void NodeJSWorkspace::GetWorkspaceFiles(wxArrayString& files) const 
{
    // Return all the files
    wxDir::GetAllFiles(GetFilename().GetPath(), &files);
}
Esempio n. 19
0
bool GenPlugin::Load()
{
	if( IsLoaded() ) return true;

	// (1) Load DLL
	hDLL = LoadLibrary( GetFullpath() );
	if( !hDLL ) return false;

	// (2) Find export
	WINAMP_GEN_GETTER winampGetGeneralPurposePlugin =
		( WINAMP_GEN_GETTER )GetProcAddress(	hDLL, "winampGetGeneralPurposePlugin" );
	if( winampGetGeneralPurposePlugin == NULL )
	{
		FreeLibrary( hDLL );
		hDLL = NULL;
		return false;
	}

	// (3) Get module
	plugin = winampGetGeneralPurposePlugin();
	if( !plugin )
	{
		FreeLibrary( hDLL );
		hDLL = NULL;
		return false;
	}

	// (4) Process module
	plugin->hDllInstance  = hDLL;
	plugin->hwndParent    = WindowMain;

	// Note:  Some plugins (mainly old ones) set description in init.
	//        Therefore we init first and copy the name after.


	// (5) Init
	if( plugin->init )
	{
		const WNDPROC WndprocBefore = ( WNDPROC )GetWindowLong( WindowMain, GWL_WNDPROC );
			plugin->init();
		const WNDPROC WndprocAfter = ( WNDPROC )GetWindowLong( WindowMain, GWL_WNDPROC );
		
		if( WndprocBefore != WndprocAfter )
		{
			WndprocBackup  = WndprocBefore;
			iHookerIndex   = iWndprocHookCounter++;
		}
	}


	if( !szName )
	{
		// Note:  The prefix is not removed to hide their
		//        origin at Nullsoft! It just reads easier.
		if( !strnicmp( plugin->description, "nullsoft ", 9 ) )
		{
			plugin->description += 9;
		}
		
		// Get rid of " (xxx.dll)" postfix
		char * walk = plugin->description + strlen( plugin->description ) - 5;
		while( true )
		{
			if( ( walk <= plugin->description ) || strnicmp( walk, ".dll)", 5 ) ) break;
			while( ( walk > plugin->description ) && ( *walk != '(' ) ) walk--;
			if( walk <= plugin->description ) break;
			walk--;
			if( ( walk <= plugin->description ) || ( *walk != ' ' ) ) break;
			*walk = '\0';
		}
		
		iNameLen = ( int )strlen( plugin->description );
		szName = new TCHAR[ iNameLen + 1 ];
		ToTchar( szName, plugin->description, iNameLen );
		szName[ iNameLen ] = TEXT( '\0' );
	}


	TCHAR szBuffer[ 5000 ];
	_stprintf( szBuffer, TEXT( "Loading <%s>, %s" ), GetFilename(), szName );
	Console::Append( szBuffer );
	Console::Append( TEXT( " " ) );


	// Note:  Plugins that use a wndproc hook need
	//        to be unloaded in the inverse loading order.
	//        This is due to the nature of wndproc hooking.
	if( iHookerIndex != -1 )
	{
		Console::Append( TEXT( "Wndproc hook added (by plugin)" ) );
	}

	return true;
}
Esempio n. 20
0
int C4MusicSystem::SetPlayList(const char *szPlayList, bool fForceSwitch, int fadetime_ms, double max_resume_time)
{
	// Shortcut if no change
	if (playlist_valid && playlist == szPlayList) return 0;
	// info
	if (::Config.Sound.Verbose)
	{
		LogF("MusicSystem: SetPlayList(\"%s\", %s, %d, %.3lf)", szPlayList ? szPlayList : "(null)", fForceSwitch ? "true" : "false", fadetime_ms, max_resume_time);
	}
	// reset
	C4MusicFile *pFile;
	for (pFile = Songs; pFile; pFile = pFile->pNext)
	{
		pFile->NoPlay = true;
	}
	ASongCount = 0;
	if (szPlayList && *szPlayList)
	{
		// match
		char szFileName[_MAX_FNAME + 1];
		for (int cnt = 0; SGetModule(szPlayList, cnt, szFileName, _MAX_FNAME); cnt++)
			for (pFile = Songs; pFile; pFile = pFile->pNext) if (pFile->NoPlay)
				if (WildcardMatch(szFileName, GetFilename(pFile->FileName)) || pFile->HasCategory(szFileName))
				{
					ASongCount++;
					pFile->NoPlay = false;
				}
	}
	else
	{
		// default: all files except the ones beginning with an at ('@')
		// Ignore frontend and credits music
		for (pFile = Songs; pFile; pFile = pFile->pNext)
			if (*GetFilename(pFile->FileName) != '@' &&
			    !pFile->HasCategory("frontend") &&
			    !pFile->HasCategory("credits"))
			{
				ASongCount++;
				pFile->NoPlay = false;
			}
	}
	// Force switch of music if currently playing piece is not in list or idle because no music file matched
	if (fForceSwitch)
	{
		if (PlayMusicFile)
		{
			fForceSwitch = PlayMusicFile->NoPlay;
		}
		else
		{
			fForceSwitch = (!is_waiting || C4TimeMilliseconds::Now() >= wait_time_end);
		}
		if (fForceSwitch)
		{
			// Switch music. Switching to a break is also allowed, but won't be done if there is a piece to resume
			// Otherwise breaks would never occur if the playlist changes often.
			Play(NULL, false, fadetime_ms, max_resume_time, PlayMusicFile != NULL);
		}
	}
	// Remember setting (e.g. to be saved in savegames)
	playlist.Copy(szPlayList);
	playlist_valid = true; // do not re-calculate available song if playlist is reset to same value in the future
	return ASongCount;
}
Esempio n. 21
0
bool CGeppetto::BuildFromInputScript(const tstring& sScript)
{
	FILE* fp = tfopen_asset(GetPath(sScript), "r");
	if (!fp)
	{
		TError("Could not read input script '" + sScript + "'\n");
		return false;
	}

	std::shared_ptr<CData> pData(new CData());
	CDataSerializer::Read(fp, pData.get());

	CData* pOutput = pData->FindChild("Output");
	if (!pOutput)
	{
		TError("Could not find Output section in input script '" + sScript + "'\n");
		return false;
	}

	CData* pGame = pData->FindChild("Game");
	if (!pGame)
	{
		TError("Could not find Game section in input script '" + sScript + "'\n");
		return false;
	}

	t.SetGameDirectory(FindAbsolutePath(GetPath(pGame->GetValueString())));

	tstring sOutputDir = ToForwardSlashes(pOutput->GetValueString());
	t.SetOutputDirectory(GetDirectory(sOutputDir));
	t.SetOutputFile(GetFilename(sOutputDir));
	t.SetScriptDirectory(GetDirectory((GetPath(sScript))));

	m_sOutput = FindAbsolutePath(t.GetGameDirectory() + T_DIR_SEP + pOutput->GetValueString());

	CData* pSceneAreas = pData->FindChild("SceneAreas");
	CData* pMesh = pData->FindChild("Mesh");
	CData* pPhysics = pData->FindChild("Physics");
	CData* pPhysicsShapes = pData->FindChild("PhysicsShapes");

	// Find all file modification times.
	time_t iScriptModificationTime = GetFileModificationTime(sScript.c_str());
	time_t iOutputModificationTime = GetFileModificationTime(m_sOutput.c_str());

	tmap<tstring, time_t> aiSceneModificationTimes;

	if (pSceneAreas)
	{
		for (size_t i = 0; i < pSceneAreas->GetNumChildren(); i++)
		{
			CData* pArea = pSceneAreas->GetChild(i);

			if (pArea->GetKey() != "Area")
				continue;

			tstring sFile = pArea->FindChildValueString("File");
			TAssert(sFile.length());
			if (!sFile.length())
				continue;

			auto it = aiSceneModificationTimes.find(sFile);
			if (it == aiSceneModificationTimes.end())
				aiSceneModificationTimes[sFile] = GetFileModificationTime(sFile.c_str());
		}
	}

	time_t iInputModificationTime = 0;
	if (pMesh)
		iInputModificationTime = GetFileModificationTime(pMesh->GetValueString().c_str());
	time_t iPhysicsModificationTime = 0;
	if (pPhysics)
		iPhysicsModificationTime = GetFileModificationTime(pPhysics->GetValueString().c_str());

	bool bRecompile = false;
	if (iScriptModificationTime > iOutputModificationTime)
		bRecompile = true;
	else if (iInputModificationTime > iOutputModificationTime)
		bRecompile = true;
	else if (iPhysicsModificationTime > iOutputModificationTime)
		bRecompile = true;
	else if (m_iBinaryModificationTime > iOutputModificationTime)
		bRecompile = true;
	else
	{
		for (auto it = aiSceneModificationTimes.begin(); it != aiSceneModificationTimes.end(); it++)
		{
			if (it->second > iOutputModificationTime)
			{
				bRecompile = true;
				break;
			}
		}
	}

	if (!bRecompile)
	{
		if (m_bForceCompile)
		{
			TMsg("Forcing rebuild even though no changes detected.\n");
		}
		else
		{
			TMsg("No changes detected. Skipping '" + m_sOutput + "'.\n\n");
			return true;
		}
	}

	CData* pGlobalTransforms = pData->FindChild("UseGlobalTransforms");
	if (pGlobalTransforms)
		t.UseGlobalTransformations();
	else
		t.UseLocalTransformations();

	t.UseUV();
	t.UseNormals();

	if (pMesh)
	{
		tstring sExtension = pMesh->GetValueString().substr(pMesh->GetValueString().length()-4);
		if (sExtension == ".png")
		{
			TUnimplemented();	// Not updated since the switch to materials.
			int x, y, n;
			unsigned char* pData = stbi_load((GetPath(pMesh->GetValueString())).c_str(), &x, &y, &n, 0);

			if (!pData)
			{
				TError("Couldn't load '" + pMesh->GetValueString() + "', reason: " + stbi_failure_reason() + "\n");
				return false;
			}

			stbi_image_free(pData); // Don't need it, just need the dimensions.

			Vector vecUp = Vector(0, 0, 0.5f) * ((float)y/100);
			Vector vecLeft = Vector(0, 0.5f, 0) * ((float)x/100);

			t.UseNormals(false);

			if (IsAbsolutePath(pMesh->GetValueString()))
				t.AddMaterial(GetPath(pMesh->GetValueString()));
			else
				t.AddMaterial(t.GetOutputDirectory() + "/" + pMesh->GetValueString(), GetPath(pMesh->GetValueString()));
			t.AddVertex(0, -vecLeft + vecUp, Vector2D(0.0f, 1.0f));
			t.AddVertex(0, -vecLeft - vecUp, Vector2D(0.0f, 0.0f));
			t.AddVertex(0, vecLeft - vecUp, Vector2D(1.0f, 0.0f));

			t.AddVertex(0, -vecLeft + vecUp, Vector2D(0.0f, 1.0f));
			t.AddVertex(0, vecLeft - vecUp, Vector2D(1.0f, 0.0f));
			t.AddVertex(0, vecLeft + vecUp, Vector2D(1.0f, 1.0f));
		}
		else if (sExtension == ".mat")
		{
			CMaterialHandle hMaterial(pMesh->GetValueString());
			if (!hMaterial.IsValid())
			{
				TError("Input material  '" + pMesh->GetValueString() + "' does not exist or is invalid.\n");
				return false;
			}

			if (!hMaterial->m_ahTextures.size())
			{
				TError("Input material  '" + pMesh->GetValueString() + "' has no textures.\n");
				return false;
			}

			float w = (float)hMaterial->m_ahTextures[0]->m_iWidth;
			float h = (float)hMaterial->m_ahTextures[0]->m_iHeight;

			Vector vecUp = Vector(0, 0.5f, 0) * (h/hMaterial->m_iTexelsPerMeter);
			Vector vecRight = Vector(0, 0, 0.5f) * (w/hMaterial->m_iTexelsPerMeter);

			t.UseNormals(false);

			t.AddMaterial(pMesh->GetValueString());

			t.AddVertex(0, -vecRight + vecUp, Vector2D(0.0f, 1.0f));
			t.AddVertex(0, -vecRight - vecUp, Vector2D(0.0f, 0.0f));
			t.AddVertex(0, vecRight - vecUp, Vector2D(1.0f, 0.0f));

			t.AddVertex(0, -vecRight + vecUp, Vector2D(0.0f, 1.0f));
			t.AddVertex(0, vecRight - vecUp, Vector2D(1.0f, 0.0f));
			t.AddVertex(0, vecRight + vecUp, Vector2D(1.0f, 1.0f));
		}
		else
		{
			TMsg("Reading model '" + GetPath(pMesh->GetValueString()) + "' ...");
			std::shared_ptr<CConversionScene> pScene(new CConversionScene());
			CModelConverter c(pScene.get());

			if (!c.ReadModel(GetPath(pMesh->GetValueString())))
			{
				TError("Couldn't read '" + GetPath(pMesh->GetValueString()) + "'.\n");
				return false;
			}
			TMsg(" Done.\n");

			TMsg("Building toy mesh ...");
			LoadSceneIntoToy(pScene.get(), &t);
			TMsg(" Done.\n");
		}
	}

	if (pPhysics)
	{
		TMsg("Reading physics model '" + GetPath(pPhysics->GetValueString()) + "' ...");
		std::shared_ptr<CConversionScene> pScene(new CConversionScene());
		CModelConverter c(pScene.get());

		if (!c.ReadModel(GetPath(pPhysics->GetValueString())))
		{
			TError("Couldn't read '" + GetPath(pPhysics->GetValueString()) + "'.\n");
			return false;
		}
		TMsg(" Done.\n");

		TMsg("Building toy physics model ...");
		LoadSceneIntoToyPhysics(pScene.get(), &t);
		TMsg(" Done.\n");
	}

	if (pPhysicsShapes)
	{
		for (size_t i = 0; i < pPhysicsShapes->GetNumChildren(); i++)
		{
			CData* pShape = pPhysicsShapes->GetChild(i);

			TAssert(pShape->GetKey() == "Box");
			if (pShape->GetKey() != "Box")
				continue;

			TRS trs = pShape->GetValueTRS();

			t.AddPhysBox(trs);
		}
	}

	if (pSceneAreas)
		LoadSceneAreas(pSceneAreas);

	return Compile();
}
Esempio n. 22
0
bool
avtGTCFileFormat::Initialize()
{
    const char *mName = "avtGTCFileFormat::Initialize: ";

    if(initialized)
        return true;

    // Init HDF5 and turn off error message printing.
    H5open();
    H5Eset_auto( NULL, NULL );

    bool err = false;

    // Check for a valid GTC file
    if( H5Fis_hdf5( GetFilename() ) < 0 )
      EXCEPTION1( InvalidFilesException, GetFilename() );

    if ((fileHandle = H5Fopen(GetFilename(), H5F_ACC_RDONLY, H5P_DEFAULT)) < 0)
      EXCEPTION1( InvalidFilesException, GetFilename() );
    
    if ((particleHandle = H5Dopen(fileHandle, "particle_data")) < 0)
    {
      H5Fclose(fileHandle);
      EXCEPTION1( InvalidFilesException, GetFilename() );
    }

    // At this point consider the file to truly be a GTC file. If
    // some other file NonCompliantExceptions will be thrown.

    // Continue as normal reporting NonCompliantExceptions

    //Check variable's size.
    hid_t dataspace = H5Dget_space(particleHandle);
    hsize_t dims[3];
    hid_t sid = H5Dget_space(particleHandle);
    int ndims = H5Sget_simple_extent_dims(dataspace, dims, NULL);
    if(ndims < 0 || ndims > 2)
    {
        debug4 << mName << "Could not determine number of dimensions" << endl;
        H5Sclose(sid);
        H5Dclose(particleHandle);
        H5Fclose(fileHandle);
        EXCEPTION1( InvalidVariableException, "GTC Dataset Extents - Dataset 'particle_data' has an invalid extents");
    }
    
    debug4 << mName << "Determining variable size" << endl;
    int val = H5Sget_simple_extent_dims(sid, dims, NULL);

    if(val < 0 || dims[1] < 3)
    {
        debug4 << mName << "Could not determine variable size" << endl;
        H5Sclose(sid);
        H5Dclose(particleHandle);
        H5Fclose(fileHandle);
        EXCEPTION1( InvalidVariableException, "GTC Dataset Extents - Dataset 'particle_data' has an insufficient number of variables");
    }
    H5Sclose(dataspace);

    debug4 << mName << "variable size (" << dims[0] << ", " << dims[1] << ")" << endl;

    nTotalPoints = dims[0];
    nVars = dims[1];

#ifdef PARALLEL
    nProcs = PAR_Size();
    rank = PAR_Rank();
    nPoints = nTotalPoints / nProcs;
    int remainder = nTotalPoints % nProcs;

    startOffset = rank * nPoints;
    if ( rank < remainder )
        startOffset += rank;
    else
        startOffset += remainder;

    if ( rank < remainder )
        nPoints++;
#else
    nPoints = nTotalPoints;
    startOffset = 0;
#endif
    
    initialized = true;
    
    return initialized;
}
Esempio n. 23
0
void C4Application::ParseCommandLine(int argc, char * argv[])
{

	StdStrBuf CmdLine("Command line:");
	for(int i = 0; i < argc; ++i) {
		CmdLine.Append(" ");
		CmdLine.Append(argv[i]);
	}
	Log(CmdLine.getData());

	ClearCommandLine();
	Game.NetworkActive = false;
	isEditor = 2;
	int c;
	while (1)
	{

		static struct option long_options[] =
		{
			// option, w/ argument?, set directly, set to...
			{"editor", no_argument, &isEditor, 1},
			{"fullscreen", no_argument, &isEditor, 0},
			{"debugwait", no_argument, &Game.DebugWait, 1},
			{"update", no_argument, &CheckForUpdates, 1},
			{"noruntimejoin", no_argument, &Config.Network.NoRuntimeJoin, 1},
			{"runtimejoin", no_argument, &Config.Network.NoRuntimeJoin, 0},
			{"noleague", no_argument, &Config.Network.LeagueServerSignUp, 0},
			{"league", no_argument, &Config.Network.LeagueServerSignUp, 1},
			{"nosignup", no_argument, &Config.Network.MasterServerSignUp, 0},
			{"signup", no_argument, &Config.Network.MasterServerSignUp, 1},
			
			{"debugrecread", required_argument, 0, 'K'},
			{"debugrecwrite", required_argument, 0, 'w'},

			{"client", required_argument, 0, 'c'},
			{"host", no_argument, 0, 'h'},
			{"debughost", required_argument, 0, 'H'},
			{"debugpass", required_argument, 0, 'P'},
			{"debug", required_argument, 0, 'D'},
			{"data", required_argument, 0, 'd'},
			{"startup", required_argument, 0, 's'},
			{"stream", required_argument, 0, 'e'},
			{"recdump", required_argument, 0, 'R'},
			{"comment", required_argument, 0, 'm'},
			{"pass", required_argument, 0, 'p'},
			{"udpport", required_argument, 0, 'u'},
			{"tcpport", required_argument, 0, 't'},
			{"join", required_argument, 0, 'j'},
			{"language", required_argument, 0, 'L'},
			{"scenpar", required_argument, 0, 'S'},

			{"observe", no_argument, 0, 'o'},
			{"nonetwork", no_argument, 0, 'N'},
			{"network", no_argument, 0, 'n'},
			{"record", no_argument, 0, 'r'},

			{"lobby", required_argument, 0, 'l'},

			{"debug-opengl", no_argument, &Config.Graphics.DebugOpenGL, 1},
			{0, 0, 0, 0}
		};
		int option_index = 0;
		c = getopt_long (argc, argv, "abc:d:f:",
			long_options, &option_index);
     		// no more options
		if (c == -1)
			break;
		switch (c)
		{
		case 0:
			// Signup
			if (SEqualNoCase(long_options[option_index].name, "signup"))
			{
				Game.NetworkActive = true;
			}
			// League
			if (SEqualNoCase(long_options[option_index].name, "league"))
			{
				Game.NetworkActive = true;
				Config.Network.MasterServerSignUp = true;
			}
			break;
		// Lobby
		case 'l':
			Game.fLobby = true;
			// lobby timeout specified? (e.g. --lobby=120)
			if (optarg)
			{
				Game.iLobbyTimeout = atoi(optarg);
				if (Game.iLobbyTimeout < 0) Game.iLobbyTimeout = 0;
			}
			break;
		case 'o': Game.fObserve = true; break;
		// Direct join
		case 'j':
			Game.NetworkActive = true;
			SCopy(optarg, Game.DirectJoinAddress, _MAX_PATH);
			break;
		case 'K':
			if (optarg && optarg[0])
			{
				LogF("Reading from DebugRec file '%s'", optarg);
				SCopy(optarg, Config.General.DebugRecExternalFile, _MAX_PATH);
			}
			else
				Log("Reading DebugRec from CtrlRec file in scenario record");
			Config.General.DebugRec = 1;
			Config.General.DebugRecWrite = 0;
			break;
		case 'w':
			if (optarg && optarg[0])
			{
				LogF("Writing to DebugRec file '%s'", optarg);
				SCopy(optarg, Config.General.DebugRecExternalFile, _MAX_PATH);
			}
			else
				Log("Writing DebugRec to CtrlRec file in scenario record");
			Config.General.DebugRec = 1;
			Config.General.DebugRecWrite = 1;
			break;
		case 'r': Game.Record = true; break;
		case 'n': Game.NetworkActive = true; break;
		case 'N': Game.NetworkActive = false; break;
		// Language override by parameter
		case 'L': SCopy(optarg, Config.General.LanguageEx, CFG_MaxString);
		// port overrides
		case 't': Config.Network.PortTCP = atoi(optarg); break;
		case 'u': Config.Network.PortUDP = atoi(optarg); break;
		// network game password
		case 'p': Network.SetPassword(optarg); break;
		// network game comment
		case 'm': Config.Network.Comment.CopyValidated(optarg); break;
		// record dump
		case 'R': Game.RecordDumpFile.Copy(optarg); break;
		// record stream
		case 'e': Game.RecordStream.Copy(optarg); break;
		// startup start screen
		case 's': C4Startup::SetStartScreen(optarg); break;
		// additional read-only data path
		case 'd': Reloc.AddPath(optarg); break;
		// debug options
		case 'D': Game.DebugPort = atoi(optarg); break;
		case 'P': Game.DebugPassword = optarg; break;
		case 'H': Game.DebugHost = optarg; break;
		// set custom scenario parameter by command line
		case 'S':
			{
			StdStrBuf sopt, soptval; sopt.Copy(optarg);
			int32_t val=1;
			if (sopt.SplitAtChar('=', &soptval)) val=atoi(soptval.getData());
			Game.StartupScenarioParameters.SetValue(sopt.getData(), val, false);
			}
			break;
		// debug configs
		case 'h':
			Game.NetworkActive = true;
			Game.fLobby = true;
			Config.Network.PortTCP = 11112;
			Config.Network.PortUDP = 11113;
			Config.Network.MasterServerSignUp = Config.Network.LeagueServerSignUp = false;
			break;
		case 'c':
			Game.NetworkActive = true;
			SCopy("localhost", Game.DirectJoinAddress, _MAX_PATH);
			Game.fLobby = true;
			Config.Network.PortTCP = 11112 + 2*(atoi(optarg)+1);
			Config.Network.PortUDP = 11113 + 2*(atoi(optarg)+1);
			break;
		case '?': /* getopt_long already printed an error message. */ break;
		default: assert(!"unexpected getopt_long return value");
		}
	}
	if (!Config.Network.MasterServerSignUp)
		Config.Network.LeagueServerSignUp = false;
	if (Game.fObserve || Game.fLobby)
		Game.NetworkActive = true;

	while (optind < argc)
	{
		char * szParameter = argv[optind++];
		{ // Strip trailing / that result from tab-completing unpacked c4groups
			int iLen = SLen(szParameter);
			if (iLen > 5 && szParameter[iLen-1] == '/' && szParameter[iLen-5] == '.' && szParameter[iLen-4] == 'o' && szParameter[iLen-3] == 'c')
			{
				szParameter[iLen-1] = '\0';
			}
		}
		// Scenario file
		if (SEqualNoCase(GetExtension(szParameter),"ocs"))
		{
			if(IsGlobalPath(szParameter))
				Game.SetScenarioFilename(szParameter);
			else
				Game.SetScenarioFilename((std::string(GetWorkingDirectory()) + DirSep + szParameter).c_str());

			continue;
		}
		if (SEqualNoCase(GetFilename(szParameter),"scenario.txt"))
		{
			Game.SetScenarioFilename(szParameter);
			continue;
		}
		// Player file
		if (SEqualNoCase(GetExtension(szParameter),"ocp"))
		{
			if(IsGlobalPath(szParameter))
				SAddModule(Game.PlayerFilenames, szParameter);
			else
				SAddModule(Game.PlayerFilenames, (std::string(GetWorkingDirectory()) + DirSep + szParameter).c_str());

			continue;
		}
		// Definition file
		if (SEqualNoCase(GetExtension(szParameter),"ocd"))
		{
			SAddModule(Game.DefinitionFilenames,szParameter);
			continue;
		}
		// Key file
		if (SEqualNoCase(GetExtension(szParameter),"c4k"))
		{
			Application.IncomingKeyfile.Copy(szParameter);
			continue;
		}
		// Update file
		if (SEqualNoCase(GetExtension(szParameter),"ocu"))
		{
			Application.IncomingUpdate.Copy(szParameter);
			continue;
		}
		// record stream
		if (SEqualNoCase(GetExtension(szParameter),"c4r"))
		{
			Game.RecordStream.Copy(szParameter);
		}
		// Direct join by URL
		if (SEqual2NoCase(szParameter, "clonk:"))
		{
			// Store address
			SCopy(szParameter + 6, Game.DirectJoinAddress, _MAX_PATH);
			SClearFrontBack(Game.DirectJoinAddress, '/');
			// Special case: if the target address is "update" then this is used for update initiation by url
			if (SEqualNoCase(Game.DirectJoinAddress, "update"))
			{
				Application.CheckForUpdates = true;
				Game.DirectJoinAddress[0] = 0;
				continue;
			}
			// Self-enable network
			Game.NetworkActive = true;
			continue;
		}
	}

#ifdef _WIN32
	// Clean up some forward/backward slach confusion since many internal OC file functions cannot handle both
	SReplaceChar(Game.ScenarioFilename, AltDirectorySeparator, DirectorySeparator);
	SReplaceChar(Game.PlayerFilenames, AltDirectorySeparator, DirectorySeparator);
	SReplaceChar(Game.DefinitionFilenames, AltDirectorySeparator, DirectorySeparator);
	Application.IncomingKeyfile.ReplaceChar(AltDirectorySeparator, DirectorySeparator);
	Application.IncomingUpdate.ReplaceChar(AltDirectorySeparator, DirectorySeparator);
	Game.RecordStream.ReplaceChar(AltDirectorySeparator, DirectorySeparator);
#endif

	// Default to editor if scenario given, player mode otherwise
	if (isEditor == 2)
		isEditor = !!*Game.ScenarioFilename && !Config.General.OpenScenarioInGameMode;

	// record?
	Game.Record = Game.Record || (Config.Network.LeagueServerSignUp && Game.NetworkActive);

	// startup dialog required?
	QuitAfterGame = !isEditor && Game.HasScenario();
}
void ReopenEditorListView::OnDoubleClick(wxListEvent& event)
{
    DoOpen(GetFilename(event.GetIndex()));
}
Esempio n. 25
0
CArchiveScanner::~CArchiveScanner()
{
	if (isDirty) {
		WriteCacheData(filesystem.LocateFile(GetFilename(), FileSystem::WRITE));
	}
}
Esempio n. 26
0
NS_IMETHODIMP 
HeaderSniffer::OnStopRequest (nsIRequest *aRequest, 
			      nsISupports *aContext, nsresult aStatusCode)
{  
	nsresult rv;
	LOG ("HeaderSniffer::OnStopRequest");

	if (aStatusCode != NS_BINDING_SUCCEEDED)
	{
		GtkWidget *parent, *dialog;

		parent = galeon_embed_persist_get_fc_parent (mEmbedPersist);

		dialog = hig_alert_new (parent ? GTK_WINDOW (parent) : NULL,
					GTK_DIALOG_DESTROY_WITH_PARENT,
					HIG_ALERT_ERROR,
					_("Unable to save link."),
					_("The web page might have been removed "
					  "or had its name changed."),
					GTK_STOCK_OK,
					GTK_RESPONSE_OK,
					NULL);
		g_signal_connect (dialog, "response",
				  (GCallback)gtk_widget_destroy, NULL);

		gtk_widget_show (dialog);
		return NS_OK;
	}

	nsCOMPtr<nsIURIChecker> checker = do_QueryInterface (aRequest);
	NS_ENSURE_TRUE (checker, NS_ERROR_FAILURE);

	nsCOMPtr<nsIChannel> channel;
	checker->GetBaseChannel (getter_AddRefs(channel));
	NS_ENSURE_TRUE (channel, NS_ERROR_FAILURE);

	/* Get the final URL of the request */
	channel->GetURI (getter_AddRefs(mFinalURL));

	/* Get the Content-Disposition header, it might give us a 
	 * hint on the filename */
	nsCOMPtr<nsIHttpChannel> httpChannel(do_QueryInterface(channel));

	GulCString contentDisposition;
	if (httpChannel)
	{
		httpChannel->GetResponseHeader(NS_LITERAL_CSTRING("content-disposition"),
					       contentDisposition);
	}

	/* Get the document encoding */
	nsCOMPtr<nsIEncodedChannel> encodedChannel(do_QueryInterface(channel));
	GulCString contentEncoding;
	if (encodedChannel)
	{
		nsCOMPtr<nsIUTF8StringEnumerator> enumerator;
		encodedChannel->GetContentEncodings (getter_AddRefs (enumerator));

		if (enumerator)
		{
			PRBool more = PR_FALSE;
			enumerator->HasMore (&more);
			
			if (more)
			{
				enumerator->GetNext (contentEncoding);
			}
		}
	}

    	/* Get the Content-Type header */
	GulCString contentType;
	channel->GetContentType(contentType);
	
	if (contentType.Equals ("application/x-unknown-content-type"))
	{
		contentType = "";
	}

	/* If no Content-Type, try and get it from the document */
	if (contentType.IsEmpty() && mDocument)
	{
		nsCOMPtr<nsIDOMNSDocument> doc = do_QueryInterface(mDocument);
		if (doc)
		{
			GulString type;
			doc->GetContentType (type);
			contentType = type;
		}
	}

	/* Failing that, guess from the url */
	if (contentType.IsEmpty())
	{
		nsCOMPtr<nsIMIMEService> mimeService (do_GetService(NS_MIMESERVICE_CONTRACTID));

		mimeService->GetTypeFromURI (mFinalURL, contentType);
	}

	/* Calculate whether we whould decode */
	mShouldDecode = PR_FALSE;

	if (contentEncoding.Length ())
	{
		nsCOMPtr<nsIExternalHelperAppService> helperService =
			do_GetService (NS_EXTERNALHELPERAPPSERVICE_CONTRACTID);

		nsCOMPtr<nsIURL> resultURL = do_QueryInterface (mFinalURL);
		if (resultURL)
		{
			GulCString extension;
			resultURL->GetFileExtension (extension);

			rv = helperService->ApplyDecodingForExtension (extension,
								       contentEncoding,
								       &mShouldDecode);

			if (NS_FAILED (rv))
			{
				mShouldDecode = PR_FALSE;
			}
		}
	}

	if (!mDocument && !mShouldDecode && contentEncoding.Length())
	{
		// The data is encoded, we are not going to decode it,
		// and this is not a document save so just set our
		// content type to correspond to the outermost
		// encoding so we get extensions and the like right.
		contentType = contentEncoding;
	}


	GulCString filename;
	rv = GetFilename (contentDisposition, contentType, filename);
	NS_ENSURE_TRUE (NS_SUCCEEDED (rv), NS_ERROR_FAILURE);

	PerformSave (filename);
	return NS_OK;
}
Esempio n. 27
0
void VideoMetadata::toMap(MetadataMap &metadataMap)
{
    if (this == NULL)
        return;

    QString coverfile;
    if (IsHostSet()
        && !GetCoverFile().startsWith("/")
        && !GetCoverFile().isEmpty()
        && !IsDefaultCoverFile(GetCoverFile()))
    {
        coverfile = generate_file_url("Coverart", GetHost(),
                GetCoverFile());
    }
    else
    {
        coverfile = GetCoverFile();
    }

    metadataMap["coverfile"] = coverfile;

    QString screenshotfile;
    if (IsHostSet() && !GetScreenshot().startsWith("/")
        && !GetScreenshot().isEmpty())
    {
        screenshotfile = generate_file_url("Screenshots",
                GetHost(), GetScreenshot());
    }
    else
    {
        screenshotfile = GetScreenshot();
    }

    metadataMap["screenshotfile"] = screenshotfile;

    QString bannerfile;
    if (IsHostSet() && !GetBanner().startsWith("/")
        && !GetBanner().isEmpty())
    {
        bannerfile = generate_file_url("Banners", GetHost(),
                GetBanner());
    }
    else
    {
        bannerfile = GetBanner();
    }

    metadataMap["bannerfile"] = bannerfile;

    QString fanartfile;
    if (IsHostSet() && !GetFanart().startsWith("/")
        && !GetFanart().isEmpty())
    {
        fanartfile = generate_file_url("Fanart", GetHost(),
                GetFanart());
    }
    else
    {
        fanartfile = GetFanart();
    }

    metadataMap["fanartfile"] = fanartfile;

    metadataMap["filename"] = GetFilename();
    metadataMap["title"] = GetTitle();
    metadataMap["subtitle"] = GetSubtitle();
    metadataMap["tagline"] = GetTagline();
    metadataMap["director"] = GetDirector();
    metadataMap["studio"] = GetStudio();
    metadataMap["description"] = GetPlot();
    metadataMap["genres"] = GetDisplayGenres(*this);
    metadataMap["countries"] = GetDisplayCountries(*this);
    metadataMap["cast"] = GetDisplayCast(*this).join(", ");
    metadataMap["rating"] = GetDisplayRating(GetRating());
    metadataMap["length"] = GetDisplayLength(GetLength());
    metadataMap["year"] = GetDisplayYear(GetYear());

    metadataMap["releasedate"] = MythDateToString(GetReleaseDate(), kDateFull);

    metadataMap["userrating"] = GetDisplayUserRating(GetUserRating());
    metadataMap["season"] = GetDisplaySeasonEpisode(GetSeason(), 1);
    metadataMap["episode"] = GetDisplaySeasonEpisode(GetEpisode(), 1);

    if (GetSeason() > 0 || GetEpisode() > 0)
    {
        metadataMap["s##e##"] = QString("s%1e%2").arg(GetDisplaySeasonEpisode
                                             (GetSeason(), 2))
                        .arg(GetDisplaySeasonEpisode(GetEpisode(), 2));
        metadataMap["##x##"] = QString("%1x%2").arg(GetDisplaySeasonEpisode
                                             (GetSeason(), 1))
                        .arg(GetDisplaySeasonEpisode(GetEpisode(), 2));
    }
    else
        metadataMap["s##e##"] = metadataMap["##x##"] = QString();

    metadataMap["trailerstate"] = TrailerToState(GetTrailer());
    metadataMap["userratingstate"] =
            QString::number((int)(GetUserRating()));
    metadataMap["watchedstate"] = WatchedToState(GetWatched());

    metadataMap["videolevel"] = ParentalLevelToState(GetShowLevel());

    metadataMap["insertdate"] = MythDateToString(GetInsertdate(), kDateFull);
    metadataMap["inetref"] = GetInetRef();
    metadataMap["homepage"] = GetHomepage();
    metadataMap["child_id"] = QString::number(GetChildID());
    metadataMap["browseable"] = GetDisplayBrowse(GetBrowse());
    metadataMap["watched"] = GetDisplayWatched(GetWatched());
    metadataMap["processed"] = GetDisplayProcessed(GetProcessed());
    metadataMap["category"] = GetCategory();
}
Esempio n. 28
0
bool C4MessageInput::ProcessCommand(const char *szCommand) {
  C4GameLobby::MainDlg *pLobby = Game.Network.GetLobby();
  // command
  char szCmdName[C4MaxName + 1];
  SCopyUntil(szCommand + 1, szCmdName, ' ', C4MaxName);
  // parameter
  const char *pCmdPar = SSearch(szCommand, " ");
  if (!pCmdPar) pCmdPar = "";

  // dev-scripts
  if (SEqual(szCmdName, "help")) {
    LogF(LoadResStr("IDS_TEXT_COMMANDSAVAILABLEDURINGGA"));
    LogF("/private [player] [message] - %s",
         LoadResStr("IDS_MSG_SENDAPRIVATEMESSAGETOTHES"));
    LogF("/team [message] - %s",
         LoadResStr("IDS_MSG_SENDAPRIVATEMESSAGETOYOUR"));
    LogF("/me [action] - %s", LoadResStr("IDS_TEXT_PERFORMANACTIONINYOURNAME"));
    LogF("/sound [sound] - %s",
         LoadResStr("IDS_TEXT_PLAYASOUNDFROMTHEGLOBALSO"));
    LogF("/kick [client] - %s", LoadResStr("IDS_TEXT_KICKTHESPECIFIEDCLIENT"));
    LogF("/observer [client] - %s",
         LoadResStr("IDS_TEXT_SETTHESPECIFIEDCLIENTTOOB"));
    LogF("/fast [x] - %s", LoadResStr("IDS_TEXT_SETTOFASTMODESKIPPINGXFRA"));
    LogF("/slow - %s", LoadResStr("IDS_TEXT_SETTONORMALSPEEDMODE"));
    LogF("/chart - %s", LoadResStr("IDS_TEXT_DISPLAYNETWORKSTATISTICS"));
    LogF("/nodebug - %s", LoadResStr("IDS_TEXT_PREVENTDEBUGMODEINTHISROU"));
    LogF("/set comment [comment] - %s",
         LoadResStr("IDS_TEXT_SETANEWNETWORKCOMMENT"));
    LogF("/set password [password] - %s",
         LoadResStr("IDS_TEXT_SETANEWNETWORKPASSWORD"));
    LogF("/set faircrew [on/off] - %s",
         LoadResStr("IDS_TEXT_ENABLEORDISABLEFAIRCREW"));
    LogF("/set maxplayer [4] - %s",
         LoadResStr("IDS_TEXT_SETANEWMAXIMUMNUMBEROFPLA"));
    LogF("/script [script] - %s", LoadResStr("IDS_TEXT_EXECUTEASCRIPTCOMMAND"));
    LogF("/clear - %s", LoadResStr("IDS_MSG_CLEARTHEMESSAGEBOARD"));
    return TRUE;
  }
  // dev-scripts
  if (SEqual(szCmdName, "script")) {
    if (!Game.IsRunning) return FALSE;
    if (!Game.DebugMode) return FALSE;
    if (!Game.Network.isEnabled() &&
        !SEqual(Game.ScenarioFile.GetMaker(), Config.General.Name) &&
        Game.ScenarioFile.GetStatus() != GRPF_Folder)
      return FALSE;
    if (Game.Network.isEnabled() && !Game.Network.isHost()) return FALSE;

    Game.Control.DoInput(
        CID_Script,
        new C4ControlScript(pCmdPar, C4ControlScript::SCOPE_Console, false),
        CDT_Decide);
    return TRUE;
  }
  // set runtimte properties
  if (SEqual(szCmdName, "set")) {
    if (SEqual2(pCmdPar, "maxplayer ")) {
      if (Game.Control.isCtrlHost()) {
        if (atoi(pCmdPar + 10) == 0 && !SEqual(pCmdPar + 10, "0")) {
          Log("Syntax: /set maxplayer count");
          return FALSE;
        }
        Game.Control.DoInput(
            CID_Set, new C4ControlSet(C4CVT_MaxPlayer, atoi(pCmdPar + 10)),
            CDT_Decide);
        return TRUE;
      }
    }
    if (SEqual2(pCmdPar, "comment ") || SEqual(pCmdPar, "comment")) {
      if (!Game.Network.isEnabled() || !Game.Network.isHost()) return FALSE;
      // Set in configuration, update reference
      Config.Network.Comment.CopyValidated(pCmdPar[7] ? (pCmdPar + 8) : "");
      Game.Network.InvalidateReference();
      Log(LoadResStr("IDS_NET_COMMENTCHANGED"));
      return TRUE;
    }
    if (SEqual2(pCmdPar, "password ") || SEqual(pCmdPar, "password")) {
      if (!Game.Network.isEnabled() || !Game.Network.isHost()) return FALSE;
      Game.Network.SetPassword(pCmdPar[8] ? (pCmdPar + 9) : NULL);
      if (pLobby) pLobby->UpdatePassword();
      return TRUE;
    }
    if (SEqual2(pCmdPar, "faircrew ")) {
      if (!Game.Control.isCtrlHost() || Game.Parameters.isLeague())
        return FALSE;
      C4ControlSet *pSet = NULL;
      if (SEqual(pCmdPar + 9, "on"))
        pSet =
            new C4ControlSet(C4CVT_FairCrew, Config.General.FairCrewStrength);
      else if (SEqual(pCmdPar + 9, "off"))
        pSet = new C4ControlSet(C4CVT_FairCrew, -1);
      else if (isdigit((unsigned char)pCmdPar[9]))
        pSet = new C4ControlSet(C4CVT_FairCrew, atoi(pCmdPar + 9));
      else
        return FALSE;
      Game.Control.DoInput(CID_Set, pSet, CDT_Decide);
      return TRUE;
    }
    // unknown property
    return FALSE;
  }
  // get szen from network folder - not in lobby; use res tab there
  if (SEqual(szCmdName, "netgetscen")) {
    if (Game.Network.isEnabled() && !Game.Network.isHost() && !pLobby) {
      const C4Network2ResCore *pResCoreScen =
          Game.Parameters.Scenario.getResCore();
      if (pResCoreScen) {
        C4Network2Res::Ref pScenario =
            Game.Network.ResList.getRefRes(pResCoreScen->getID());
        if (pScenario)
          if (C4Group_CopyItem(
                  pScenario->getFile(),
                  Config.AtExePath(GetFilename(Game.ScenarioFilename)))) {
            LogF(LoadResStr("IDS_MSG_CMD_NETGETSCEN_SAVED"),
                 Config.AtExePath(GetFilename(Game.ScenarioFilename)));
            return TRUE;
          }
      }
    }
    return FALSE;
  }
  // clear message board
  if (SEqual(szCmdName, "clear")) {
    // lobby
    if (pLobby) {
      pLobby->ClearLog();
    }
    // fullscreen
    else if (Game.GraphicsSystem.MessageBoard.Active)
      Game.GraphicsSystem.MessageBoard.ClearLog();
    else {
      // EM mode
      Console.ClearLog();
    }
    return TRUE;
  }
  // kick client
  if (SEqual(szCmdName, "kick")) {
    if (Game.Network.isEnabled() && Game.Network.isHost()) {
      // find client
      C4Client *pClient = Game.Clients.getClientByName(pCmdPar);
      if (!pClient) {
        LogF(LoadResStr("IDS_MSG_CMD_NOCLIENT"), pCmdPar);
        return FALSE;
      }
      // league: Kick needs voting
      if (Game.Parameters.isLeague() &&
          Game.Players.GetAtClient(pClient->getID()))
        Game.Network.Vote(VT_Kick, true, pClient->getID());
      else
        // add control
        Game.Clients.CtrlRemove(pClient,
                                LoadResStr("IDS_MSG_KICKFROMMSGBOARD"));
    }
    return TRUE;
  }
  // set fast mode
  if (SEqual(szCmdName, "fast")) {
    if (!Game.IsRunning) return FALSE;
    if (Game.Parameters.isLeague()) {
      Log(LoadResStr("IDS_LOG_COMMANDNOTALLOWEDINLEAGUE"));
      return FALSE;
    }
    int32_t iFS;
    if ((iFS = atoi(pCmdPar)) == 0) return FALSE;
    // set frameskip and fullspeed flag
    Game.FrameSkip = BoundBy<int32_t>(iFS, 1, 500);
    Game.FullSpeed = TRUE;
    // start calculation immediatly
    Application.NextTick(false);
    return TRUE;
  }
  // reset fast mode
  if (SEqual(szCmdName, "slow")) {
    if (!Game.IsRunning) return FALSE;
    Game.FullSpeed = FALSE;
    Game.FrameSkip = 1;
    return TRUE;
  }

  if (SEqual(szCmdName, "nodebug")) {
    if (!Game.IsRunning) return FALSE;
    Game.Control.DoInput(CID_Set, new C4ControlSet(C4CVT_AllowDebug, false),
                         CDT_Decide);
    return TRUE;
  }

  if (SEqual(szCmdName, "msgboard")) {
    if (!Game.IsRunning) return FALSE;
    // get line cnt
    int32_t iLineCnt = BoundBy(atoi(pCmdPar), 0, 20);
    if (iLineCnt == 0)
      Game.GraphicsSystem.MessageBoard.ChangeMode(2);
    else if (iLineCnt == 1)
      Game.GraphicsSystem.MessageBoard.ChangeMode(0);
    else {
      Game.GraphicsSystem.MessageBoard.iLines = iLineCnt;
      Game.GraphicsSystem.MessageBoard.ChangeMode(1);
    }
    return TRUE;
  }

  // kick/activate/deactivate/observer
  if (SEqual(szCmdName, "activate") || SEqual(szCmdName, "deactivate") ||
      SEqual(szCmdName, "observer")) {
    if (!Game.Network.isEnabled() || !Game.Network.isHost()) {
      Log(LoadResStr("IDS_MSG_CMD_HOSTONLY"));
      return FALSE;
    }
    // search for client
    C4Client *pClient = Game.Clients.getClientByName(pCmdPar);
    if (!pClient) {
      LogF(LoadResStr("IDS_MSG_CMD_NOCLIENT"), pCmdPar);
      return FALSE;
    }
    // what to do?
    C4ControlClientUpdate *pCtrl = NULL;
    if (szCmdName[0] == 'a')  // activate
      pCtrl = new C4ControlClientUpdate(pClient->getID(), CUT_Activate, true);
    else if (szCmdName[0] == 'd' && !Game.Parameters.isLeague())  // deactivate
      pCtrl = new C4ControlClientUpdate(pClient->getID(), CUT_Activate, false);
    else if (szCmdName[0] == 'o' && !Game.Parameters.isLeague())  // observer
      pCtrl = new C4ControlClientUpdate(pClient->getID(), CUT_SetObserver);
    // perform it
    if (pCtrl)
      Game.Control.DoInput(CID_ClientUpdate, pCtrl, CDT_Sync);
    else
      Log(LoadResStr("IDS_LOG_COMMANDNOTALLOWEDINLEAGUE"));
    return TRUE;
  }

  // control mode
  if (SEqual(szCmdName, "centralctrl") || SEqual(szCmdName, "decentralctrl") ||
      SEqual(szCmdName, "asyncctrl")) {
    if (!Game.Network.isEnabled() || !Game.Network.isHost()) {
      Log(LoadResStr("IDS_MSG_CMD_HOSTONLY"));
      return FALSE;
    }
    if (Game.Parameters.isLeague() && *szCmdName == 'a') {
      Log(LoadResStr("IDS_LOG_COMMANDNOTALLOWEDINLEAGUE"));
      return FALSE;
    }
    Game.Network.SetCtrlMode(
        *szCmdName == 'c' ? CNM_Central : *szCmdName == 'd' ? CNM_Decentral
                                                            : CNM_Async);
    return TRUE;
  }

  // show chart
  if (Game.IsRunning)
    if (SEqual(szCmdName, "chart")) return Game.ToggleChart();

  // custom command
  C4MessageBoardCommand *pCmd;
  if (Game.IsRunning)
    if (pCmd = GetCommand(szCmdName)) {
      StdStrBuf Script, CmdScript;
      // replace %player% by calling player number
      if (SSearch(pCmd->Script, "%player%")) {
        int32_t iLocalPlr = NO_OWNER;
        C4Player *pLocalPlr = Game.Players.GetLocalByIndex(0);
        if (pLocalPlr) iLocalPlr = pLocalPlr->Number;
        StdStrBuf sLocalPlr;
        sLocalPlr.Format("%d", iLocalPlr);
        CmdScript.Copy(pCmd->Script);
        CmdScript.Replace("%player%", sLocalPlr.getData());
      } else {
        CmdScript.Ref(pCmd->Script);
      }
      // insert parameters
      if (SSearch(CmdScript.getData(), "%d")) {
        // make sure it's a number by converting
        Script.Format(CmdScript.getData(), (int)atoi(pCmdPar));
      } else if (SSearch(CmdScript.getData(), "%s")) {
        // Unrestricted parameters?
        // That's kind of a security risk as it will allow anyone to execute
        // code
        switch (pCmd->eRestriction) {
          case C4MessageBoardCommand::C4MSGCMDR_Escaped: {
            // escape strings
            StdStrBuf Par;
            Par.Copy(pCmdPar);
            Par.EscapeString();
            // compose script
            Script.Format(CmdScript.getData(), Par.getData());
          } break;

          case C4MessageBoardCommand::C4MSGCMDR_Plain:
            // unescaped
            Script.Format(CmdScript.getData(), pCmdPar);
            break;

          case C4MessageBoardCommand::C4MSGCMDR_Identifier: {
            // only allow identifier-characters
            StdStrBuf Par;
            while (IsIdentifier(*pCmdPar) || isspace((unsigned char)*pCmdPar))
              Par.AppendChar(*pCmdPar++);
            // compose script
            Script.Format(CmdScript.getData(), Par.getData());
          } break;
        }
      } else
        Script = CmdScript.getData();
      // add script
      Game.Control.DoInput(CID_Script, new C4ControlScript(Script.getData()),
                           CDT_Decide);
      // ok
      return TRUE;
    }

  // unknown command
  StdStrBuf sErr;
  sErr.Format(LoadResStr("IDS_ERR_UNKNOWNCMD"), szCmdName);
  if (pLobby)
    pLobby->OnError(sErr.getData());
  else
    Log(sErr.getData());
  return FALSE;
}
Esempio n. 29
0
/**
 * @brief get the basename part of a path, ie. the filename without extension
 */
std::string FileSystem::GetBasename(const std::string& path) const
{
	std::string fn = GetFilename(path);
	return fn.substr(0, fn.find_last_of('.'));
}
Esempio n. 30
0
 void GetPlatformBinaryFilename(char *szDest, VTargetPlatform_e targetPlatform) const
 {
   GetPlatformBinaryFilename(GetFilename(),szDest,targetPlatform);
 }