本文整理汇总了C++中FileStream类的典型用法代码示例。如果您正苦于以下问题:C++ FileStream类的具体用法?C++ FileStream怎么用?C++ FileStream使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了FileStream类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: MIKTEX_ASSERT_STRING_OR_NIL
bool
Process::Run (/*[in]*/ const PathName & fileName,
/*[in]*/ const char * lpszArguments,
/*[out]*/ IRunProcessCallback * pCallback,
/*[out]*/ int * pExitCode,
/*[in]*/ const char * lpszWorkingDirectory)
{
MIKTEX_ASSERT_STRING_OR_NIL (lpszArguments);
MIKTEX_ASSERT_STRING_OR_NIL (lpszWorkingDirectory);
ProcessStartInfo startinfo;
startinfo.FileName = fileName.Get();
if (lpszArguments != 0)
{
startinfo.Arguments = lpszArguments;
}
startinfo.StandardInput = 0;
startinfo.RedirectStandardInput = false;
startinfo.RedirectStandardOutput = (pCallback != 0);
startinfo.RedirectStandardError = false;
if (lpszWorkingDirectory != 0)
{
startinfo.WorkingDirectory = lpszWorkingDirectory;
}
auto_ptr<Process> pProcess (Process::Start(startinfo));
if (pCallback != 0)
{
SessionImpl::GetSession()->trace_process->WriteLine
("core",
T_("start reading the pipe"));
const size_t CHUNK_SIZE = 64;
char buf[ CHUNK_SIZE ];
bool cancelled = false;
FileStream stdoutStream (pProcess->get_StandardOutput());
size_t total = 0;
while (! cancelled && feof(stdoutStream.Get()) == 0)
{
size_t n = fread(buf, 1, CHUNK_SIZE, stdoutStream.Get());
int err = ferror(stdoutStream.Get());
if (err != 0 && err != EPIPE)
{
FATAL_CRT_ERROR ("fread", 0);
}
// pass output to caller
total += n;
cancelled = ! pCallback->OnProcessOutput(buf, n);
}
SessionImpl::GetSession()->trace_process->WriteFormattedLine
("core",
T_("read %u bytes from the pipe"),
static_cast<unsigned>(total));
}
// wait for the process to finish
pProcess->WaitForExit ();
// get the exit code & close process
int exitCode = pProcess->get_ExitCode();
pProcess->Close ();
if (pExitCode != 0)
{
*pExitCode = exitCode;
return (true);
}
else if (exitCode == 0)
{
return (true);
}
else
{
TraceError (T_("%s returned %d"),
Q_(fileName),
static_cast<int>(exitCode));
return (false);
}
}
示例2: HELIUM_ASSERT
/// @copydoc ResourceHandler::CacheResource()
bool ShaderResourceHandler::CacheResource(
AssetPreprocessor* pAssetPreprocessor,
Resource* pResource,
const String& rSourceFilePath )
{
HELIUM_ASSERT( pAssetPreprocessor );
HELIUM_ASSERT( pResource );
const Shader* pShader = Reflect::AssertCast< const Shader >( pResource );
AssetPath shaderPath = pShader->GetPath();
HELIUM_TRACE( TraceLevels::Info, TXT( "ShaderResourceHandler: Caching \"%s\".\n" ), *shaderPath.ToString() );
DefaultAllocator allocator;
FileStream* pSourceFileStream = FileStream::OpenFileStream( rSourceFilePath, FileStream::MODE_READ );
if( !pSourceFileStream )
{
HELIUM_TRACE(
TraceLevels::Error,
TXT( "ShaderResourceHandler: Source file for shader resource \"%s\" failed to open properly.\n" ),
*shaderPath.ToString() );
return false;
}
// Load the entire shader resource into memory.
int64_t size64 = pSourceFileStream->GetSize();
HELIUM_ASSERT( size64 != -1 );
HELIUM_ASSERT( static_cast< uint64_t >( size64 ) <= static_cast< size_t >( -1 ) );
if( size64 > static_cast< uint64_t >( static_cast< size_t >( -1 ) ) )
{
HELIUM_TRACE(
TraceLevels::Error,
( TXT( "ShaderResourceHandler: Source file for shader resource \"%s\" is too large to fit into " )
TXT( "memory for preprocessing.\n" ) ),
*shaderPath.ToString() );
delete pSourceFileStream;
return false;
}
size_t size = static_cast< size_t >( size64 );
void* pShaderData = allocator.Allocate( size );
HELIUM_ASSERT( pShaderData );
if( !pShaderData )
{
HELIUM_TRACE(
TraceLevels::Error,
( TXT( "ShaderResourceHandler: Failed to allocate %" ) PRIuSZ TXT( " bytes for loading the source " )
TXT( "data of \"%s\" for preprocessing.\n" ) ),
size,
*shaderPath.ToString() );
delete pSourceFileStream;
return false;
}
BufferedStream( pSourceFileStream ).Read( pShaderData, 1, size );
delete pSourceFileStream;
// Parse all preprocessor toggle and selection tokens from the shader source.
StrongPtr< Shader::PersistentResourceData > resourceData( new Shader::PersistentResourceData() );
const char* pLineEnd = static_cast< const char* >( pShaderData );
const char* pShaderEnd = pLineEnd + size;
do
{
const char* pLineStart = pLineEnd;
while( pLineEnd < pShaderEnd )
{
char character = *pLineEnd;
if( character == '\n' || character == '\r' )
{
break;
}
++pLineEnd;
}
ParseLine( shaderPath, *resourceData, pLineStart, pLineEnd );
while( pLineEnd < pShaderEnd )
{
char character = *pLineEnd;
if( character != '\n' && character != '\r' )
{
break;
}
++pLineEnd;
}
} while( pLineEnd < pShaderEnd );
//.........这里部分代码省略.........
示例3: mh
// ReceiveFileData
//------------------------------------------------------------------------------
bool ToolManifest::ReceiveFileData( uint32_t fileId, const void * data, size_t & dataSize )
{
MutexHolder mh( m_Mutex );
File & f = m_Files[ fileId ];
// gracefully handle multiple receipts of the same data
if ( f.m_Content )
{
ASSERT( f.m_SyncState == File::SYNCHRONIZED );
return true;
}
ASSERT( f.m_SyncState == File::SYNCHRONIZING );
// prepare name for this file
AStackString<> fileName;
GetRemoteFilePath( fileId, fileName );
// prepare destination
AStackString<> pathOnly( fileName.Get(), fileName.FindLast( NATIVE_SLASH ) );
if ( !FileIO::EnsurePathExists( pathOnly ) )
{
return false; // FAILED
}
// write to disk
FileStream fs;
if ( !fs.Open( fileName.Get(), FileStream::WRITE_ONLY ) )
{
return false; // FAILED
}
if ( fs.Write( data, dataSize ) != dataSize )
{
return false; // FAILED
}
fs.Close();
// open read-only
AutoPtr< FileStream > fileStream( FNEW( FileStream ) );
if ( fileStream.Get()->Open( fileName.Get(), FileStream::READ_ONLY ) == false )
{
return false; // FAILED
}
// This file is now synchronized
f.m_FileLock = fileStream.Release(); // NOTE: Keep file open to prevent deletion
f.m_SyncState = File::SYNCHRONIZED;
// is completely synchronized?
const File * const end = m_Files.End();
for ( const File * it = m_Files.Begin(); it != end; ++it )
{
if ( it->m_SyncState != File::SYNCHRONIZED )
{
// still some files to be received
return true; // file stored ok
}
}
// all files received
m_Synchronized = true;
return true; // file stored ok
}
示例4: JustPath
// Extracts specified files from zip
void ZipFile::Extract(String* FileSpec, String* DestPath, UpdateOption OverwriteWhen, Boolean RecurseSubdirectories, PathInclusion CreatePathMethod)
{
// Any file spec in destination path will be ignored
DestPath = JustPath(DestPath);
char* pszPassword = NULL;
char* pszFileName = NULL;
OpenFileForUnzip();
// Just wrapping in a try/catch/finally to make sure unmanaged code allocations always get released
try
{
Regex* filePattern = GetFilePatternRegularExpression(FileSpec, caseSensitive);
IEnumerator* filesEnum = files->GetEnumerator();
CompressedFile* file;
String* sourceFileName;
String* destFileName;
bool writeFile;
int err;
// Get ANSI password, if one was provided
if (password)
if (password->get_Length())
pszPassword = StringToCharBuffer(password);
// Loop through compressed file collection
while (filesEnum->MoveNext())
{
file = static_cast<CompressedFile*>(filesEnum->Current);
sourceFileName = file->get_FileName();
if (filePattern->IsMatch(GetSearchFileName(FileSpec, sourceFileName, RecurseSubdirectories)))
{
pszFileName = StringToCharBuffer(sourceFileName);
err = unzLocateFile(hUnzipFile, pszFileName, (caseSensitive ? 1 : 2));
free(pszFileName);
pszFileName = NULL;
// We should find file in zip file if it was in our compressed file collection
if (err != Z_OK) throw new CompressionException(String::Concat(S"Extract Zip File Error: Compressed file \"", sourceFileName, "\" cannot be found in zip file!"));
// Open compressed file for unzipping
if (pszPassword)
err = unzOpenCurrentFilePassword(hUnzipFile, pszPassword);
else
err = unzOpenCurrentFile(hUnzipFile);
if (err != Z_OK) throw new CompressionException(S"Extract Zip File", err);
// Get full destination file name
switch (CreatePathMethod)
{
case PathInclusion::FullPath:
destFileName = sourceFileName;
break;
case PathInclusion::NoPath:
destFileName = String::Concat(DestPath, Path::GetFileName(sourceFileName));
break;
case PathInclusion::RelativePath:
destFileName = String::Concat(DestPath, sourceFileName);
break;
}
// Make sure destination directory exists
Directory::CreateDirectory(JustPath(destFileName));
// See if destination file already exists
if (File::Exists(destFileName))
{
DateTime lastUpdate = File::GetLastWriteTime(destFileName);
switch (OverwriteWhen)
{
case UpdateOption::Never:
writeFile = false;
break;
case UpdateOption::Always:
writeFile = true;
break;
case UpdateOption::ZipFileIsNewer:
writeFile = (DateTime::Compare(file->get_FileDateTime(), lastUpdate) > 0);
break;
case UpdateOption::DiskFileIsNewer:
writeFile = (DateTime::Compare(file->get_FileDateTime(), lastUpdate) < 0);
break;
default:
writeFile = false;
break;
}
}
else
writeFile = true;
if (writeFile)
{
System::Byte buffer[] = new System::Byte[BufferSize];
System::Byte __pin * destBuff = &buffer[0]; // pin buffer so it can be safely passed into unmanaged code...
FileStream* fileStream = File::Create(destFileName);
int read;
//.........这里部分代码省略.........
示例5: cb_tell
long OggSoundFile::cb_tell(void* source)
{
FileStream *file = static_cast<FileStream*>(source);
return file->tell();
}
示例6: storeModule
bool storeModule( Options& options, Module* mod )
{
// this is the base path for the module
Path modPath( mod->path() );
Path tgtPath;
tgtPath.setFullLocation( options.m_sTargetDir );
// normalize module path
while( modPath.getFullLocation().startsWith("./") )
{
modPath.setFullLocation( modPath.getFullLocation().subString(2) );
}
message( String("Processing module ").A( modPath.get() ) );
// strip the main script path from the module path.
String modloc = modPath.getFullLocation();
if ( modloc.find( options.m_sMainScriptPath ) == 0 )
{
// The thing came from below the main script.
modloc = modloc.subString(options.m_sMainScriptPath.length() );
if ( modloc != "" && modloc.getCharAt(0) == '/' )
{
modloc = modloc.subString(1);
}
tgtPath.setFullLocation( tgtPath.get() + "/" + modloc );
}
else
{
// if it's coming from somewhere else in the loadpath hierarcy,
// we must store it below the topmost dir.
tgtPath.setFullLocation( tgtPath.get() + "/" + options.m_sSystemRoot );
// Find the path in LoadPath that caused this module to load,
// strip it away and reproduce it below the SystemRoot.
// For example, strip /usr/lib/falcon/ from system scripts.
std::vector<String> paths;
splitPaths( options.m_sLoadPath, paths );
for( uint32 i = 0; i < paths.size(); ++i )
{
if( modloc.startsWith( paths[i] ) )
{
String sSysPath = modloc.subString( paths[i].size() + 1 );
if( sSysPath != "" )
{
tgtPath.setFullLocation( tgtPath.get() + "/" + sSysPath );
}
break;
}
}
}
// store it
int fsStatus;
if ( ! Sys::fal_mkdir( tgtPath.getFullLocation(), fsStatus, true ) )
{
error( String("Can't create ") + tgtPath.getFullLocation() );
return false;
}
tgtPath.setFilename( modPath.getFilename() );
// should we store just sources, just fam or both?
if( modPath.getExtension() != "fam" && modPath.getExtension() != DllLoader::dllExt() )
{
// it's a source file.
if ( ! options.m_bStripSources )
{
if( ! copyFile( modPath.get(), tgtPath.get() ) )
{
error( String("Can't copy \"") + modPath.get() + "\" into \"" +
tgtPath.get() + "\"" );
return false;
}
}
// should we save the fam?
if( options.m_bStripSources || options.m_bPackFam )
{
tgtPath.setExtension("fam");
FileStream famFile;
if ( ! famFile.create( tgtPath.get(), (Falcon::BaseFileStream::t_attributes) 0644 )
|| ! mod->save(&famFile) )
{
error( "Can't create \"" + tgtPath.get() + "\"" );
return false;
}
famFile.flush();
famFile.close();
}
}
else
{
// just blindly copy everything else.
if( ! copyFile( modPath.get(), tgtPath.get() ) )
{
//.........这里部分代码省略.........
示例7: HELIUM_ASSERT
//.........这里部分代码省略.........
DynArray< Shader::SelectPair > selectPairs;
rUserOptions.GetOptionSetFromIndex( shaderType, userOptionIndex, toggleNames, selectPairs );
DynArray< PlatformPreprocessor::ShaderToken > shaderTokens;
size_t userToggleNameCount = toggleNames.GetSize();
for( size_t toggleNameIndex = 0; toggleNameIndex < userToggleNameCount; ++toggleNameIndex )
{
PlatformPreprocessor::ShaderToken* pToken = shaderTokens.New();
HELIUM_ASSERT( pToken );
StringConverter< tchar_t, char >::Convert( pToken->name, *toggleNames[ toggleNameIndex ] );
pToken->definition = "1";
}
size_t userSelectPairCount = selectPairs.GetSize();
for( size_t selectPairIndex = 0; selectPairIndex < userSelectPairCount; ++selectPairIndex )
{
const Shader::SelectPair& rPair = selectPairs[ selectPairIndex ];
PlatformPreprocessor::ShaderToken* pToken = shaderTokens.New();
HELIUM_ASSERT( pToken );
StringConverter< tchar_t, char >::Convert( pToken->name, *rPair.name );
pToken->definition = "1";
pToken = shaderTokens.New();
HELIUM_ASSERT( pToken );
StringConverter< tchar_t, char >::Convert( pToken->name, *rPair.choice );
pToken->definition = "1";
}
size_t userShaderTokenCount = shaderTokens.GetSize();
// Load the entire shader resource into memory.
FileStream* pSourceFileStream = File::Open( rSourceFilePath, FileStream::MODE_READ );
if( !pSourceFileStream )
{
HELIUM_TRACE(
TRACE_ERROR,
( TXT( "ShaderVariantResourceHandler: Source file for shader variant resource \"%s\" failed to open " )
TXT( "properly.\n" ) ),
*pVariant->GetPath().ToString() );
return false;
}
int64_t size64 = pSourceFileStream->GetSize();
HELIUM_ASSERT( size64 != -1 );
HELIUM_ASSERT( static_cast< uint64_t >( size64 ) <= static_cast< size_t >( -1 ) );
if( size64 > static_cast< uint64_t >( static_cast< size_t >( -1 ) ) )
{
HELIUM_TRACE(
TRACE_ERROR,
( TXT( "ShaderVariantResourceHandler: Source file for shader resource \"%s\" is too large to fit " )
TXT( "into memory for preprocessing.\n" ) ),
*pShader->GetPath().ToString() );
delete pSourceFileStream;
return false;
}
size_t size = static_cast< size_t >( size64 );
DefaultAllocator allocator;
void* pShaderSource = allocator.Allocate( size );
示例8: ImportAnm
void LOLExporter::ImportAnm( const String& anmFilename )
{
FileStream file;
if (!file.Open(anmFilename))
{
printf("ERROR: could not open %s\n", anmFilename.c_str());
exit(1);
}
char id[8];
file.Read(id, sizeof(id));
uint32_t version = file.ReadUInt();
mLOLAnimation.Version = version;
// Version 0, 1, 2, 3 Code
if (version == 0 || version == 1 || version == 2 || version == 3)
{
uint32_t magic = file.ReadUInt();
uint32_t numBones = file.ReadUInt();
uint32_t numFrames = file.ReadUInt();
uint32_t playbackFPS = file.ReadUInt();
char nameBuffer[32];
// Read in all the bones
mLOLAnimation.Clip.AnimationTracks.resize(numBones);
for (uint32_t i = 0; i < numBones; ++i)
{
LOLAnimation::AnimationClip::AnimationTrack& animTrack = mLOLAnimation.Clip.AnimationTracks[i];
file.Read(nameBuffer, sizeof(nameBuffer));
animTrack.BoneName = nameBuffer;
// Unknown
uint32_t boneType = file.ReadUInt();
// For each bone, read in its value at each frame in the animation.
animTrack.KeyFrames.resize(numFrames);
for (LOLAnimation::AnimationClip::KeyFrame& frame : animTrack.KeyFrames)
{
// Read in the frame's quaternion.
frame.Orientation[3] = file.ReadFloat(); // x
frame.Orientation[1] = file.ReadFloat(); // y
frame.Orientation[2] = file.ReadFloat(); // z
frame.Orientation[0] = file.ReadFloat(); // w
// Read in the frame's position.
file.Read(&frame.Position, sizeof(float3));
}
}
}
else if (version == 4)
{
uint32_t magic = file.ReadUInt();
// Not sure what any of these mean.
float unknown = file.ReadFloat();
unknown = file.ReadFloat();
unknown = file.ReadFloat();
uint32_t numBones = file.ReadUInt();
uint32_t numFrames = file.ReadUInt();
uint32_t playbackFPS = (uint32_t)(1.0f / file.ReadFloat() + 0.5f);
// These are offsets to specific data sections in the file.
uint32_t unknownOffset = file.ReadUInt();
unknownOffset = file.ReadUInt();
unknownOffset = file.ReadUInt();
uint32_t positionOffset = file.ReadUInt();
uint32_t orientationOffset = file.ReadUInt();
uint32_t indexOffset = file.ReadUInt();
// These last three values are confusing.
// They aren't a vector and they throw off the offset values
// by 12 bytes. Just ignore them and keep reading.
unknownOffset = file.ReadUInt();
unknownOffset = file.ReadUInt();
unknownOffset = file.ReadUInt();
//
// Vector section.
//
std::vector<float> positions;
uint32_t numPositions = (orientationOffset - positionOffset) / sizeof(float);
for (uint32_t i = 0; i < numPositions; ++i)
positions.push_back(file.ReadFloat());
//
// Quaternion section.
//
std::vector<float> orientations;
uint32_t numOrientations = (indexOffset - orientationOffset) / sizeof(float);
for (uint32_t i = 0; i < numOrientations; ++i)
orientations.push_back(file.ReadFloat());
//
//.........这里部分代码省略.........
示例9: ImportSkl
void LOLExporter::ImportSkl( const String& sklFilename )
{
FileStream stream;
if (!stream.Open(sklFilename))
{
printf("ERROR: could not open %s\n", sklFilename.c_str());
exit(1);
}
char id[8];
stream.Read(id, 8);
mLOLSkeleton.Version = stream.ReadUInt();
if (mLOLSkeleton.Version == 1 || mLOLSkeleton.Version == 2)
{
uint32_t designerID = stream.ReadUInt();
char nameBuffer[32];
float matrix[12];
// Read in the bones.
uint32_t numBones = stream.ReadUInt();
mLOLSkeleton.Bones.resize(numBones);
for (uint32_t i = 0; i < numBones; ++i)
{
LOLBone& bone = mLOLSkeleton.Bones[i];
stream.Read(nameBuffer, 32);
bone.Name = nameBuffer;
bone.Index = i;
bone.ParentIndex = stream.ReadInt();
bone.Scale = stream.ReadFloat();
// Read in transform matrix.
stream.Read(matrix, sizeof(matrix));
float4x4 rotation(
matrix[0], matrix[4], matrix[8], 0.0f,
matrix[1], matrix[5], matrix[9], 0.0f,
matrix[2], matrix[6], matrix[10], 0.0f,
0.0f, 0.0f, 0.0f, 1.0f);
bone.Orientation = QuaternionFromRotationMatrix(rotation);
bone.Position = float3(matrix[3], matrix[7], matrix[11]);
}
// Version two contains bone IDs.
if (mLOLSkeleton.Version == 2)
{
uint32_t numBoneIDs = stream.ReadUInt();
for (uint32_t i = 0; i < numBoneIDs; ++i)
mLOLSkeleton.BoneIDs.push_back(stream.ReadUInt());
}
}
else if (mLOLSkeleton.Version == 0)
{
uint16_t zero = stream.ReadUShort();
uint16_t numBones = stream.ReadUShort();
uint32_t numBoneIDs = stream.ReadUInt();
uint16_t offsetToVertexData = stream.ReadUShort(); // Should be 64.
int unknown = stream.ReadShort(); // ?
int offset1 = stream.ReadInt();
int offsetToAnimationIndices = stream.ReadInt();
int offset2 = stream.ReadInt();
int offset3 = stream.ReadInt();
int offsetToStrings = stream.ReadInt();
// Not sure what this data represents.
// I think it's padding incase more header data is required later.
//stream.Seek(stream.GetPosition() + 20);
mLOLSkeleton.Bones.resize(numBones);
stream.Seek(offsetToVertexData);
for (int i = 0; i < numBones; ++i)
{
LOLBone& bone = mLOLSkeleton.Bones[i];
// The old scale was always 0.1. For now, just go with it.
bone.Scale = 0.1f;
zero = stream.ReadShort(); // ?
bone.Index = stream.ReadShort();
bone.ParentIndex = stream.ReadShort();
unknown = stream.ReadShort(); // ?
int namehash = stream.ReadInt();
float twoPointOne = stream.ReadFloat();
stream.Read(&bone.Position, sizeof(float3));
float one = stream.ReadFloat(); // ? Maybe scales for X, Y, and Z
one = stream.ReadFloat();
one = stream.ReadFloat();
stream.Read(&bone.Orientation, sizeof(Quaternionf));
float ctx = stream.ReadFloat(); // ctx
//.........这里部分代码省略.........
示例10: ImportSkn
void LOLExporter::ImportSkn( const String& sknFilename )
{
FileStream file;
if (!file.Open(sknFilename))
{
printf("ERROR: could not open %s\n", sknFilename.c_str());
exit(1);
}
uint32_t magic = file.ReadInt();
uint16_t version = file.ReadUShort();
uint16_t numObjects = file.ReadUShort();
mLOLSkinMesh.Version = version;
if (version == 1 || version == 2)
{
// Contains material headers.
uint32_t numParts = file.ReadUInt();
char nameBuffer[64];
mLOLSkinMesh.MeshParts.resize(numParts);
for (uint32_t i = 0; i < numParts; ++i)
{
// Read in the headers.
LOLSkinMesh::MeshPart& meshPart = mLOLSkinMesh.MeshParts[i];
file.Read(nameBuffer, sizeof(nameBuffer));
meshPart.Material = nameBuffer;
meshPart.StartVertex = file.ReadInt();
meshPart.VertexCount = file.ReadUInt();
meshPart.StartIndex = file.ReadInt();
meshPart.IndexCount = file.ReadUInt();
}
uint32_t numIndices = file.ReadUInt();
uint32_t numVertices = file.ReadUInt();
mLOLSkinMesh.Indices.resize(numIndices);
file.Read(&mLOLSkinMesh.Indices[0], numIndices * sizeof(uint16_t));
mLOLSkinMesh.Verteces.resize(numVertices);
for (LOLSkinMesh::Vertex& vertex : mLOLSkinMesh.Verteces)
{
file.Read(&vertex.Position, sizeof(float3));
file.Read(&vertex.BoneIndices, sizeof(uint8_t)*4);
file.Read(&vertex.BoneWeights, sizeof(float)*4);
file.Read(&vertex.Normal, sizeof(float3));
file.Read(&vertex.Texcoords, sizeof(float2));
// Check SkinModelVertex
/*float totalWeight = 0.0f;
for (int i = 0; i < 4; ++i)
{
if (vertex.BoneIndices[i] >= mBones.size())
printf("Bone Index Out of Range!");
totalWeight += vertex.weights[i];
}
if ( fabsf(totalWeight - 1.0f) > 0.001)
printf("Unnormalized Bone Weights!");
if ( vertex.texcoords[0] < 0.0f || vertex.texcoords[0] > 1.0f ||
vertex.texcoords[1] < 0.0f || vertex.texcoords[1] > 1.0f )
printf("Texcoords Index Out of Range!");*/
}
for ( size_t i = 0; i < mLOLSkinMesh.MeshParts.size(); ++i )
{
LOLSkinMesh::MeshPart& lolMeshPart = mLOLSkinMesh.MeshParts[i];
const int32_t StartIndex = lolMeshPart.StartIndex;
const int32_t EndIndex = lolMeshPart.StartIndex + lolMeshPart.IndexCount;
for (int32_t j = StartIndex; j < EndIndex; ++j)
{
uint16_t index = mLOLSkinMesh.Indices[j];
const LOLSkinMesh::Vertex& vertex = mLOLSkinMesh.Verteces[index];
lolMeshPart.Bound.Merge(vertex.Position);
}
mLOLSkinMesh.Bound.Merge(lolMeshPart.Bound);
}
}
else
{
printf("Unsupported Skn format!\n");
exit(1);
}
printf("SkinnedMesh %s\n", sknFilename.c_str());
printf("Version: %d\n", mLOLSkinMesh.Version);
printf("Number of Objects: %d\n", numObjects);
printf("Number of Material Headers: %d\n", mLOLSkinMesh.MeshParts.size());
printf("Number of Vertices: %d\n", mLOLSkinMesh.Verteces.size());
printf("Number of Indices: %d\n", mLOLSkinMesh.Indices.size());
}
示例11: Map_LoadFile
/*
================
Map_LoadFile
================
*/
void Map_LoadFile( const char *filename ){
clock_t start, finish;
double elapsed_time;
start = clock();
Sys_BeginWait();
Select_Deselect();
/*!
\todo FIXME TTimo why is this commented out?
stability issues maybe? or duplicate feature?
forcing to show the console during map load was a good thing IMO
*/
//SetInspectorMode(W_CONSOLE);
Sys_Printf( "Loading map from %s\n", filename );
Map_Free();
//++timo FIXME: maybe even easier to have Group_Init called from Map_Free?
Group_Init();
g_qeglobals.d_num_entities = 0;
g_qeglobals.d_parsed_brushes = 0;
// cancel the map loading process
// used when conversion between standard map format and BP format is required and the user cancels the process
g_bCancel_Map_LoadFile = false;
strcpy( currentmap, filename );
g_bScreenUpdates = false; // leo: avoid redraws while loading the map (see fenris:1952)
// prepare to let the map module do the parsing
FileStream file;
const char* type = strrchr( filename,'.' );
if ( type != NULL ) {
type++;
}
// NOTE TTimo opening has binary doesn't make a lot of sense
// but opening as text confuses the scriptlib parser
// this may be a problem if we "rb" and use the XML parser, might have an incompatibility
if ( file.Open( filename, "rb" ) ) {
Map_Import( &file, type );
}
else{
Sys_FPrintf( SYS_ERR, "ERROR: failed to open %s for read\n", filename );
}
file.Close();
g_bScreenUpdates = true;
if ( g_bCancel_Map_LoadFile ) {
Sys_Printf( "Map_LoadFile canceled\n" );
Map_New();
Sys_EndWait();
return;
}
if ( !world_entity ) {
Sys_Printf( "No worldspawn in map.\n" );
Map_New();
Sys_EndWait();
return;
}
finish = clock();
elapsed_time = (double)( finish - start ) / CLOCKS_PER_SEC;
Sys_Printf( "--- LoadMapFile ---\n" );
Sys_Printf( "%s\n", filename );
Sys_Printf( "%5i brushes\n", g_qeglobals.d_parsed_brushes );
Sys_Printf( "%5i entities\n", g_qeglobals.d_num_entities );
Sys_Printf( "%5.2f second(s) load time\n", elapsed_time );
Sys_EndWait();
Map_RestoreBetween();
//
// move the view to a start position
//
Map_StartPosition();
Map_RegionOff();
modified = false;
Sys_SetTitle( filename );
Texture_ShowInuse();
QERApp_SortActiveShaders();
Sys_UpdateWindows( W_ALL );
}
示例12: fBuild
REGISTER_TESTS_END
// TestStaleDynamicDeps
//------------------------------------------------------------------------------
void TestObject::TestStaleDynamicDeps() const
{
const char* fileA = "../../../../ftmp/Test/Object/StaleDynamicDeps/GeneratedInput/FileA.h";
const char* fileB = "../../../../ftmp/Test/Object/StaleDynamicDeps/GeneratedInput/FileB.h";
const char* fileC = "../../../../ftmp/Test/Object/StaleDynamicDeps/GeneratedInput/FileC.h";
const char* database = "../../../../ftmp/Test/Object/StaleDynamicDeps/fbuild.fdb";
// Generate some header files
{
// Need FBuild for CleanPath
FBuildOptions options;
FBuild fBuild( options );
// Ensure output path exists
AStackString<> fullOutputPath;
NodeGraph::CleanPath( AStackString<>( fileA ), fullOutputPath );
TEST_ASSERT( Node::EnsurePathExistsForFile( fullOutputPath ) );
// Create files
FileStream f;
TEST_ASSERT( f.Open( fileA, FileStream::WRITE_ONLY ) );
f.Close();
TEST_ASSERT( f.Open( fileB, FileStream::WRITE_ONLY ) );
f.Close();
TEST_ASSERT( f.Open( fileC, FileStream::WRITE_ONLY ) );
f.Close();
}
// Build CPP Generator
{
// Init
FBuildOptions options;
options.m_ConfigFile = "Data/TestObject/StaleDynamicDeps/cppgenerator.bff";
options.m_ForceCleanBuild = true;
FBuild fBuild( options );
TEST_ASSERT( fBuild.Initialize() );
// Compile
TEST_ASSERT( fBuild.Build( AStackString<>( "CPPGenerator" ) ) );
}
// Build using CPP Generator (clean)
{
// Init
FBuildOptions options;
options.m_ConfigFile = "Data/TestObject/StaleDynamicDeps/staledeps.bff";
options.m_ForceCleanBuild = true;
options.m_ShowSummary = true; // required to generate stats for node count checks
FBuild fBuild( options );
TEST_ASSERT( fBuild.Initialize() );
// Compile
TEST_ASSERT( fBuild.Build( AStackString<>( "StaleDynamicDeps" ) ) );
// Save DB
TEST_ASSERT( fBuild.SaveDependencyGraph( database ) );
// Check stats
// Seen, Built, Type
CheckStatsNode ( 1, 1, Node::DIRECTORY_LIST_NODE );
CheckStatsNode ( 2, 2, Node::COMPILER_NODE );
CheckStatsNode ( 4, 4, Node::OBJECT_NODE ); // 3xCPPGen + 1xUnity
}
// Delete one of the generated headers
EnsureFileDoesNotExist( fileB );
// Work around poor time resolution of file system on OSX by waiting at least 1 second
// TODO:C Changes to the way dependencies are managed might make this unnecessary
#if defined( __OSX__ )
Thread::Sleep(1001);
#endif
// Build Again
{
// Init
FBuildOptions options;
options.m_ConfigFile = "Data/TestObject/StaleDynamicDeps/staledeps.bff";
options.m_ShowSummary = true; // required to generate stats for node count checks
FBuild fBuild( options );
TEST_ASSERT( fBuild.Initialize( database ) );
// Compile
TEST_ASSERT( fBuild.Build( AStackString<>( "StaleDynamicDeps" ) ) );
// Check stats
// Seen, Built, Type
CheckStatsNode ( 1, 1, Node::DIRECTORY_LIST_NODE );
CheckStatsNode ( 2, 0, Node::COMPILER_NODE );
CheckStatsNode ( 3, 1, Node::OBJECT_NODE ); // 3xCPPGen + 1xUnity, rebuild of unity
}
}
示例13: BuildCacheCRC
bool StandardMainLoop::handleCommandLine( S32 argc, const char **argv )
{
// Allow the window manager to process command line inputs; this is
// done to let web plugin functionality happen in a fairly transparent way.
PlatformWindowManager::get()->processCmdLineArgs(argc, argv);
Process::handleCommandLine( argc, argv );
// Set up the command line args for the console scripts...
Con::setIntVariable("Game::argc", argc);
U32 i;
std::vector<const char*> arguments;
arguments.push_back(StringTable->insert("main"));
for (i = 1; i < argc; i++)
{
Con::setVariable(avar("Game::argv%d", i), argv[i]);
if (i > 0)
{
arguments.push_back(argv[i]);
}
}
//WLE - Vince
if (Winterleaf_EngineCallback::mWLE_GlobalFunction!=0)
{
char sbuffer[8000];
Winterleaf_EngineCallback::mWLE_GlobalFunction(argc , &arguments[0], sbuffer);
//If you can find the main routine in C# then use it, if it fails use stock.
if (atoi(sbuffer))
{
BuildCacheCRC();
return true;
}
}
#ifdef TORQUE_PLAYER
if(argc > 2 && dStricmp(argv[1], "-project") == 0)
{
char playerPath[1024];
Platform::makeFullPathName(argv[2], playerPath, sizeof(playerPath));
Platform::setCurrentDirectory(playerPath);
argv += 2;
argc -= 2;
// Re-locate the game:/ asset mount.
Torque::FS::Unmount( "game" );
Torque::FS::Mount( "game", Platform::FS::createNativeFS( playerPath ) );
}
#endif
// Executes an entry script file. This is "main.cs"
// by default, but any file name (with no whitespace
// in it) may be run if it is specified as the first
// command-line parameter. The script used, default
// or otherwise, is not compiled and is loaded here
// directly because the resource system restricts
// access to the "root" directory.
#ifdef TORQUE_ENABLE_VFS
Zip::ZipArchive *vfs = openEmbeddedVFSArchive();
bool useVFS = vfs != NULL;
#endif
Stream *mainCsStream = NULL;
// The working filestream.
FileStream str;
const char *defaultScriptName = "main.cs";
bool useDefaultScript = true;
// Check if any command-line parameters were passed (the first is just the app name).
if (argc > 1)
{
// If so, check if the first parameter is a file to open.
if ( (dStrcmp(argv[1], "") != 0 ) && (str.open(argv[1], Torque::FS::File::Read)) )
{
// If it opens, we assume it is the script to run.
useDefaultScript = false;
#ifdef TORQUE_ENABLE_VFS
useVFS = false;
#endif
mainCsStream = &str;
}
}
if (useDefaultScript)
{
bool success = false;
#ifdef TORQUE_ENABLE_VFS
if(useVFS)
success = (mainCsStream = vfs->openFile(defaultScriptName, Zip::ZipArchive::Read)) != NULL;
else
#endif
success = str.open(defaultScriptName, Torque::FS::File::Read);
//.........这里部分代码省略.........
示例14: dStrdup
bool GFXGLShader::_loadShaderFromStream( GLuint shader,
const Torque::Path &path,
FileStream *s,
const Vector<GFXShaderMacro> ¯os )
{
Vector<char*> buffers;
Vector<U32> lengths;
// The GLSL version declaration must go first!
const char *versionDecl = "#version 150\r\n";
buffers.push_back( dStrdup( versionDecl ) );
lengths.push_back( dStrlen( versionDecl ) );
if(gglHasExtension(EXT_gpu_shader4))
{
const char *extension = "#extension GL_EXT_gpu_shader4 : enable\r\n";
buffers.push_back( dStrdup( extension ) );
lengths.push_back( dStrlen( extension ) );
}
if(gglHasExtension(ARB_gpu_shader5))
{
const char *extension = "#extension GL_ARB_gpu_shader5 : enable\r\n";
buffers.push_back( dStrdup( extension ) );
lengths.push_back( dStrlen( extension ) );
}
const char *newLine = "\r\n";
buffers.push_back( dStrdup( newLine ) );
lengths.push_back( dStrlen( newLine ) );
// Now add all the macros.
for( U32 i = 0; i < macros.size(); i++ )
{
if(macros[i].name.isEmpty()) // TODO OPENGL
continue;
String define = String::ToString( "#define %s %s\n", macros[i].name.c_str(), macros[i].value.c_str() );
buffers.push_back( dStrdup( define.c_str() ) );
lengths.push_back( define.length() );
}
// Now finally add the shader source.
U32 shaderLen = s->getStreamSize();
char *buffer = _handleIncludes(path, s);
if ( !buffer )
return false;
buffers.push_back(buffer);
lengths.push_back(shaderLen);
glShaderSource(shader, buffers.size(), (const GLchar**)const_cast<const char**>(buffers.address()), NULL);
#if defined(TORQUE_DEBUG) && defined(TORQUE_DEBUG_GFX)
FileStream stream;
if ( !stream.open( path.getFullPath()+"_DEBUG", Torque::FS::File::Write ) )
{
AssertISV(false, avar("GFXGLShader::initShader - failed to write debug shader '%s'.", path.getFullPath().c_str()));
}
for(int i = 0; i < buffers.size(); ++i)
stream.writeText(buffers[i]);
#endif
// Cleanup the shader source buffer.
for ( U32 i=0; i < buffers.size(); i++ )
dFree( buffers[i] );
glCompileShader(shader);
return true;
}
示例15: Format
void Renderer::Execute()
{
Network::Packet* packet = m_Net->RecvNonBlocking(0);
if (packet != NULL)
{
Kernel::GetInstance()->Log(m_LogTag | Logger::IS_INFORMATION, "Got package: %s", packet->GetID());
// Some sort of data we need for rendering future pipeline
if (packet->GetTag() == m_NetTag_Datacache)
{
if (StringCompare(packet->GetID(), "res") == 0)
{
unsigned long hash = packet->GetObject<unsigned long>(0);
char* filename = packet->GetArray<char*>(packet->ObjectSize(1), 1);
unsigned long datalen = packet->GetObject<unsigned long>(2);
char* data = packet->GetArray<char*>(packet->ObjectSize(3) ,3);
char location[256];
Format(location, "datacache/%X_%s", (unsigned int)hash, filename);
Kernel::GetInstance()->Log(m_LogTag | Logger::IS_INFORMATION, "Saving data to cache: %s", location);
FileStream stream;
stream.OpenWriteBinary(location);
stream.Write(data, datalen);
stream.Close();
delete [] filename;
delete [] data;
m_NumRecieved++;
Network::Packet* ackpack = m_NetDevice->CreateEmptyPacket("ackres", m_NetTag_Datacache);
ackpack->PushInt(m_NumRecieved);
m_Net->SendAllPacket(ackpack);
delete ackpack;
}
else if (StringCompare(packet->GetID(), "ack") == 0)
{
// has_everything_lets_do_some_rendering()
}
}
// New pipeline to render
else if (packet->GetTag() == m_NetTag_Pipeline)
{
m_SendPreviews = true;
CleanUp();
m_JsonDataSize = packet->GetLength();
m_JsonData = new char[m_JsonDataSize];
StringCopy(m_JsonData, packet->GetData(), m_JsonDataSize);
//Kernel::GetInstance()->Log(m_LogTag | Logger::IS_INFORMATION, "Got new pipeline data, loading JSON and building graph: %s", m_JsonData);
Kernel::GetInstance()->Log(m_LogTag | Logger::IS_INFORMATION, "Got new pipeline data, loading JSON and building graph.");
LoadJson();
BuildGraph();
m_NumRecieved = 0;
if (m_RootBlock)
{
m_RootBlock->ResetPerformed();
m_RootBlock->Execute(m_SendPreviews);
m_SendPreviews = false;
/*if (m_Net->NumClients() > 0)
{
Resource::Image* img = m_gfx->CreateImageFromTexture(GetResult());
Network::Packet* imgpacket = m_NetDevice->CreateEmptyPacket("imgdata", m_NetTag_Preview);
imgpacket->PushInt(img->Width());
imgpacket->PushInt(img->Height());
imgpacket->PushInt(img->Channels());
imgpacket->PushString((const char*)img->Ptr(), img->Height()*img->Width()*img->Channels());
Kernel::GetInstance()->Log(m_LogTag | Logger::IS_INFORMATION, "Sending final image to client '%d'", packet->GetSender());
m_Net->SendAllPacket(imgpacket);
m_NumRecieved = 0;
delete imgpacket;
delete img;
}*/
}
else
{
Kernel::GetInstance()->Log(m_LogTag | Logger::IS_CRITICAL, "Failed to execute root block since it's NULL.");
}
}
}
if (m_RootBlock)
{
m_RootBlock->ResetPerformed();
m_RootBlock->Execute(m_SendPreviews);
m_SendPreviews = false;
}
else
{
Kernel::GetInstance()->Log(m_LogTag | Logger::IS_CRITICAL, "Failed to execute root block since it's NULL.");
}
//.........这里部分代码省略.........