Example #1
0
bool MetaFileSystem::MkDir(const std::string &dirname)
{
	std::lock_guard<std::recursive_mutex> guard(lock);
	std::string of;
	IFileSystem *system;
	if (MapFilePath(dirname, of, &system))
	{
		return system->MkDir(of);
	}
	else
	{
		return false;
	}
}
Example #2
0
bool MetaFileSystem::RenameFile(const std::string &from, const std::string &to)
{
	std::string of;
	std::string rf;
	IFileSystem *system;
	if (MapFilePath(from, of, &system) && MapFilePath(to, rf, &system))
	{
		return system->RenameFile(of, rf);
	}
	else
	{
		return false;
	}
}
Example #3
0
std::vector<PSPFileInfo> MetaFileSystem::GetDirListing(std::string path)
{
	std::string of;
	IFileSystem *system;
	if (MapFilePath(path, of, &system))
	{
		return system->GetDirListing(of);
	}
	else
	{
		std::vector<PSPFileInfo> empty;
		return empty;
	}
}
Example #4
0
bool MetaFileSystem::RmDir(const std::string &dirname)
{
	lock_guard guard(lock);
	std::string of;
	IFileSystem *system;
	if (MapFilePath(dirname, of, &system))
	{
		return system->RmDir(of);
	}
	else
	{
		return false;
	}
}
Example #5
0
PSPFileInfo MetaFileSystem::GetFileInfo(std::string filename)
{
	std::string of;
	IFileSystem *system;
	if (MapFilePath(filename, of, &system))
	{
		return system->GetFileInfo(of);
	}
	else
	{
		PSPFileInfo bogus; // TODO
		return bogus; 
	}
}
Example #6
0
bool MetaFileSystem::RemoveFile(const std::string &filename)
{
	lock_guard guard(lock);
	std::string of;
	IFileSystem *system;
	if (MapFilePath(filename, of, &system))
	{
		return system->RemoveFile(of);
	}
	else
	{
		return false;
	}
}
Example #7
0
std::vector<FileInfo> MetaFileSystem::GetDirListing(std::string path)
{
	std::lock_guard<std::recursive_mutex> guard(lock);
	std::string of;
	IFileSystem *system;
	if (MapFilePath(path, of, &system))
	{
		return system->GetDirListing(of);
	}
	else
	{
		std::vector<FileInfo> empty;
		return empty;
	}
}
Example #8
0
IFileSystem* CreateFileSystem(const IVolume* _rVolume)
{
	IFileSystem* pFileSystem = new CFileSystemGCWii(_rVolume);

	if (!pFileSystem)
		return nullptr;

	if (!pFileSystem->IsValid())
	{
		delete pFileSystem;
		pFileSystem = nullptr;
	}

	return pFileSystem;
}
Example #9
0
FileInfo MetaFileSystem::GetFileInfo(std::string filename)
{
	std::lock_guard<std::recursive_mutex> guard(lock);
	std::string of;
	IFileSystem *system;
	if (MapFilePath(filename, of, &system))
	{
		return system->GetFileInfo(of);
	}
	else
	{
		FileInfo bogus; // TODO
		return bogus; 
	}
}
Example #10
0
bool
CMNGAnimation::Load(const char* filename, IFileSystem& fs)
{
  this->~CMNGAnimation();

  // open the file
  m_file = fs.Open(filename, IFileSystem::read);
  if (m_file == NULL) {
    return false;
  }

  // initialize MNG playback
  m_stream = mng_initialize(this, CB_Allocate, CB_Free, NULL);

  // set all of the callbacks
  mng_setcb_openstream(m_stream, CB_OpenStream);
  mng_setcb_closestream(m_stream, CB_CloseStream);
  mng_setcb_readdata(m_stream, CB_ReadData);
  mng_setcb_processheader(m_stream, CB_ProcessHeader);
  mng_setcb_gettickcount(m_stream, CB_GetTickCount);
  mng_setcb_getcanvasline(m_stream, CB_GetCanvasLine);
  mng_setcb_refresh(m_stream, CB_Refresh);
  mng_setcb_settimer(m_stream, CB_SetTimer);

  // do some reading
  if (mng_read(m_stream) != MNG_NOERROR) {
    return false;
  }

  return true;
}
Example #11
0
bool
CConfigFile::Load(const char* filename, IFileSystem& fs)
{
    m_sections.erase(m_sections.begin(), m_sections.end());

    // open the file
    IFile* file = fs.Open(filename, IFileSystem::read);
    if (file == NULL) {
        return false;
    }

    std::string current_section = "";

    bool eof = false;
    while (!eof) {
        // read a line
        std::string line;
        eof = !read_line(file, line);
        const char* string = line.c_str();

        // parse it

        // eliminate whitespace
        skip_whitespace(string);

        if (string[0] == '[') {  // it's a section
            string++;

            current_section = "";
            while (*string != ']') {
                current_section += *string++;
            }
            string++;
        } else {                 // it's a key=value pair

            // read key
            std::string key;
            while (*string != '=' && *string) {
                key += *string++;
            }

            if (*string == 0) {
                continue; // skip lines without equals
            }
            string++; // skip the '='

            std::string value;
            while (*string) {
                value += *string++;
            }

            // add the item
            WriteString(current_section.c_str(), key.c_str(), value.c_str());
        }
    }

    file->Close();
    return true;
}
Example #12
0
bool
sTileset::Load(const char* filename, IFileSystem& fs)
{
  IFile* file = fs.Open(filename, IFileSystem::read);
  if (file == NULL)
    return false;

  bool result = LoadFromFile(file);

  file->Close();
  return result;
}
void PrintDetailedPlayerClassStats()
{
	if ( !tf_DetailedStats.GetInt() )
		return;

	IFileSystem *pFileSys = filesystem;

	FileHandle_t hFile = pFileSys->Open( "class_stats_detailed.txt", "wt", "LOGDIR" );
	if ( hFile != FILESYSTEM_INVALID_HANDLE )
	{
		// Print the header.
		for ( int i=TFCLASS_UNDECIDED+1; i < STATS_NUM_GROUPS; i++ )
		{
			pFileSys->FPrintf( hFile, "%s dist\t%s dmg\t", GetGroupNameFor( i ), GetGroupNameFor( i ) );
		}
		pFileSys->FPrintf( hFile, "\n" );

		// Write out each column.
		int iterators[STATS_NUM_GROUPS];
		for ( i=TFCLASS_UNDECIDED+1; i < STATS_NUM_GROUPS; i++ )
			iterators[i] = g_ClassShotInfos[i].Head();

		bool bWroteAnything;
		do
		{
			bWroteAnything = false;
			for ( int i=TFCLASS_UNDECIDED+1; i < STATS_NUM_GROUPS; i++ )
			{
				if ( iterators[i] == g_ClassShotInfos[i].InvalidIndex() )
				{
					pFileSys->FPrintf( hFile, "\t\t" );
				}
				else
				{
					CShotInfo *pInfo = &g_ClassShotInfos[i][iterators[i]];
					iterators[i] = g_ClassShotInfos[i].Next( iterators[i] );

					pFileSys->FPrintf( hFile, "%.2f\t%d\t", pInfo->m_flDistance, pInfo->m_nDamage );
					bWroteAnything = true;
				}
			}
			pFileSys->FPrintf( hFile, "\n" );

		} while ( bWroteAnything );


		pFileSys->Close( hFile );
	}
}
Example #14
0
bool
sTileset::Save(const char* filename, IFileSystem& fs) const
{
  // open the file
  IFile* file = fs.Open(filename, IFileSystem::write);
  if (file == NULL)
    return false;

  bool result = SaveToFile(file);

  file->Close();
  return result;
}
Example #15
0
bool
CConfigFile::Save(const char* filename, IFileSystem& fs) const
{
    IFile* file = fs.Open(filename, IFileSystem::write);
    if (file == NULL) {
        return false;
    }

    // find the section without a name and write that first
    std::map<std::string, Section>::const_iterator i;
    for (i = m_sections.begin(); i != m_sections.end(); i++) {
        if (i->first == "") {
            const Section& s = i->second;

            std::map<std::string, std::string>::const_iterator j;
            for (j = s.entries.begin(); j != s.entries.end(); j++) {
                write_string(file, j->first);
                file->Write("=", 1);
                write_string(file, j->second);
                file->Write("\n", 1);
            }

            file->Write("\n", 1);
        }
    }

    // write the rest of the sections
    for (i = m_sections.begin(); i != m_sections.end(); i++) {
        if (i->first != "") {
            file->Write("[", 1);
            write_string(file, i->first);
            file->Write("]\n", 2);

            const Section& s = i->second;
            std::map<std::string, std::string>::const_iterator j;
            for (j = s.entries.begin(); j != s.entries.end(); j++) {
                write_string(file, j->first);
                file->Write("=", 1);
                write_string(file, j->second);
                file->Write("\n", 1);
            }

            file->Write("\n", 1);

        }
    }

    file->Close();
    return true;
}
CString WindowManager::LoadJson(IFileSystem& fileSystem, const CString& cszRelativeFilename)
{
   std::shared_ptr<Stream::IStream> spStream =
      fileSystem.OpenFile(cszRelativeFilename, true);

   Stream::TextStreamFilter stream(*spStream,
      Stream::ITextStream::textEncodingAnsi,
      Stream::ITextStream::lineEndingNative);

   CString cszLine, cszText;
   while (!stream.AtEndOfStream())
   {
      stream.ReadLine(cszLine);
      cszText += cszLine;
      cszText += _T("\r\n");
   }

   return cszText;
}
Example #17
0
void MetaFileSystem::CloseFile(u32 handle)
{
	IFileSystem *sys = GetHandleOwner(handle);
	if (sys)
		sys->CloseFile(handle);
}
Example #18
0
// Operations dealing with encrypted space are done here - the volume is swapped to allow this
bool ParsePartitionData(SPartition& _rPartition)
{
	bool ParsedOK = true;

	// Switch out the main volume temporarily
	IVolume *OldVolume = m_Disc;

	// Ready some stuff
	m_Disc = CreateVolumeFromFilename(m_Filename, _rPartition.GroupNumber, _rPartition.Number);
	IFileSystem *FileSystem = CreateFileSystem(m_Disc);

	if (!FileSystem)
	{
		ERROR_LOG(DISCIO, "Failed to create filesystem for group %d partition %u", _rPartition.GroupNumber, _rPartition.Number);
		ParsedOK = false;
	}
	else
	{
		std::vector<const SFileInfo *> Files;
		size_t numFiles = FileSystem->GetFileList(Files);

		// Mark things as used which are not in the filesystem
		// Header, Header Information, Apploader
		ReadFromVolume(0x2440 + 0x14, 4, _rPartition.Header.ApploaderSize);
		ReadFromVolume(0x2440 + 0x18, 4, _rPartition.Header.ApploaderTrailerSize);
		MarkAsUsedE(_rPartition.Offset
			+ _rPartition.Header.DataOffset
			, 0
			, 0x2440
			+ _rPartition.Header.ApploaderSize
			+ _rPartition.Header.ApploaderTrailerSize);

		// DOL
		ReadFromVolume(0x420, 4, _rPartition.Header.DOLOffset);
		_rPartition.Header.DOLSize = GetDOLSize(_rPartition.Header.DOLOffset);
		MarkAsUsedE(_rPartition.Offset
			+ _rPartition.Header.DataOffset
			, _rPartition.Header.DOLOffset
			, _rPartition.Header.DOLSize);

		// FST
		ReadFromVolume(0x424, 4, _rPartition.Header.FSTOffset);
		ReadFromVolume(0x428, 4, _rPartition.Header.FSTSize);
		MarkAsUsedE(_rPartition.Offset
			+ _rPartition.Header.DataOffset
			, _rPartition.Header.FSTOffset
			, _rPartition.Header.FSTSize);

		// Go through the filesystem and mark entries as used
		for (size_t currentFile = 0; currentFile < numFiles; currentFile++)
		{
			DEBUG_LOG(DISCIO, "%s", currentFile ? (*Files.at(currentFile)).m_FullPath : "/");
			// Just 1byte for directory? - it will end up reserving a cluster this way
			if ((*Files.at(currentFile)).m_NameOffset & 0x1000000)
				MarkAsUsedE(_rPartition.Offset
				+ _rPartition.Header.DataOffset
				, (*Files.at(currentFile)).m_Offset, 1);
			else
				MarkAsUsedE(_rPartition.Offset
				+ _rPartition.Header.DataOffset
				, (*Files.at(currentFile)).m_Offset, (*Files.at(currentFile)).m_FileSize);
		}
	}

	delete FileSystem;

	// Swap back
	delete m_Disc;
	m_Disc = OldVolume;

	return ParsedOK;
}
Example #19
0
	bool CShaderHLSL::Create(P3D::sShaderDesc &desc)
	{
		const char *pData;
		ULONG fsize;
		IFileSystem* pFS = CRenderer::mEngine()->mFilesystem();
		wchar path[P3DMAX_PATH];
		wsprintf(path, P3DMAX_PATH-1, _W("shaders/%s.rshader"), desc.ShaderFile.Get());
		FSFILE *fp = pFS->Load(path, (BYTE *&)pData, fsize, true);
		if (!fp)
		{
			CON(MSG_ERR, _W("Can't open %s.hlsl shader file from data/shaders directory!"), desc.ShaderFile.Get());
			return false;
		}

		ID3DXBuffer *pShaderBlob = NULL;
		ID3DXBuffer *pErrors = NULL;
		DWORD flags = D3DXSHADER_DEBUG;  //D3DXSHADER_OPTIMIZATION_LEVEL3

		char profile[128];
		switch(desc.ShaderType)
		{
		case SHADERTYPE_VERTEX_SHADER:
			strcpy(profile, D3DXGetVertexShaderProfile(g_pD3ddev));
			break;
		case SHADERTYPE_PIXEL_SHADER:
			strcpy(profile, D3DXGetPixelShaderProfile(g_pD3ddev));
			break;
		case SHADERTYPE_GEOMETRY_SHADER:
			CON(MSG_ERR, _W("DX9 does not support geometry shaders."));
			return false;
		default:
			CON(MSG_ERR, _W("Chader creation failed. No apropriate ShaderType given."));
			return false;
		}

		CIncludeHandler includeHandler;
		
		D3DXMACRO Shader_Macros[] = 
		{
			{ "DX9", NULL },
			{ "SM3", NULL },
			NULL
		};

		if(FAILED(D3DXCompileShader(
			pData, 
			fsize, 
			Shader_Macros, 
			&includeHandler, 
			_W2A(desc.EntryFunction.Get()), 
			profile, 
			flags,
			&pShaderBlob, 
			&pErrors,
			&m_pConstTable
			)))
		{
			if(pErrors) CON(MSG_ERR, _W("%s"), _A2W((char*)pErrors->GetBufferPointer()));
			else CON(MSG_ERR, _W("Error description not given"));
			CON(MSG_ERR, _W("Shader %s could not be compiled"), desc.ShaderFile.Get());
			SAFE_RELEASE(pErrors);
			return false;
		}

		pFS->UnLoad(fp, (BYTE *)pData);

		//save to cache
		fp = pFS->Open(_W("cache/shaders/hlsl"), _W("wb"));
		const char* cs = (const char*)pShaderBlob->GetBufferPointer();
		pFS->Write(cs, 1, pShaderBlob->GetBufferSize(), fp);
		pFS->Close(fp);

		bool shaderCreated = false;
		switch(desc.ShaderType)
		{
		case SHADERTYPE_VERTEX_SHADER:
			shaderCreated = SUCCEEDED(g_pD3ddev->CreateVertexShader((const DWORD*)pShaderBlob->GetBufferPointer(), &m_pVS));
			break;
		case SHADERTYPE_PIXEL_SHADER:
			shaderCreated = SUCCEEDED(g_pD3ddev->CreatePixelShader((const DWORD*)pShaderBlob->GetBufferPointer(), &m_pPS));
			break;
		}

		if(!shaderCreated)
		{
			CON(MSG_ERR, _W("Shader creation error"));
			return false;
		}

		//set constant to their default values 
		m_pConstTable->SetDefaults(g_pD3ddev);

		//create vertex declaration
		if(desc.ShaderType == SHADERTYPE_VERTEX_SHADER)
			m_pVertDecl = new CVertexDeclaration(CRenderer::cGraphicsManager()->GetVertexDescByID(desc.VertexDescID), pShaderBlob);

		SAFE_RELEASE(pShaderBlob);

		m_desc = desc;

		CON(MSG_INFO, _W("Shader '%s' created"), desc.ShaderFile);

		return true;
	}
Example #20
0
/*
The start of the main function starts like in most other example. We ask the
user for the desired renderer and start it up. This time with the advanced
parameter handling.
*/
int main()
{
	// create device with full flexibility over creation parameters
	// you can add more parameters if desired, check irr::SIrrlichtCreationParameters
	irr::SIrrlichtCreationParameters params;
	params.DriverType= video::EDT_DIRECT3D9;
	params.WindowSize=core::dimension2d<u32>(1024, 768);
	IrrlichtDevice* device = createDeviceEx(params);

	if (device == 0)
		return 1; // could not create selected driver.

	
	/*
	First, we add standard stuff to the scene: A nice irrlicht engine
	logo, a small help text, a user controlled camera, and we disable
	the mouse cursor.
	*/

	video::IVideoDriver* driver = device->getVideoDriver();
	scene::ISceneManager* smgr = device->getSceneManager();
	gui::IGUIEnvironment* env = device->getGUIEnvironment();
	IFileSystem* filesys = device->getFileSystem();

	driver->setTextureCreationFlag(video::ETCF_ALWAYS_32_BIT, true);

	SKeyMap keyMap[4];
	keyMap[0].Action = EKA_MOVE_FORWARD;
	keyMap[0].KeyCode = KEY_UP;
	keyMap[1].Action = EKA_MOVE_BACKWARD;
	keyMap[1].KeyCode = KEY_DOWN;
	keyMap[2].Action = EKA_STRAFE_LEFT;
	keyMap[2].KeyCode = KEY_LEFT;
	keyMap[3].Action = EKA_STRAFE_RIGHT;
	keyMap[3].KeyCode = KEY_RIGHT;


	// add camera
	camera = smgr->addCameraSceneNodeFPS(0,100.0f,0.5f, -1, keyMap, 4);

	camera->setPosition(core::vector3df(-168, 283, -168));
	camera->setTarget(core::vector3df(60,137,83));
	camera->setFarValue(42000.0f);

	// disable mouse cursor
	device->getCursorControl()->setVisible(false);

	// create event receiver
	MyEventReceiver receiver;
	device->setEventReceiver(&receiver);

	smgr->setAmbientLight(video::SColorf(0.1,0.1,0.1,1));

	ITerrainSceneNode* floorNode = smgr->addTerrainSceneNode(0, 0, -1, vector3df(0, 0, 0), vector3df(0, 0, 0), vector3df(1, 1, 1), SColor(255, 255, 255, 255), 5, ETPS_17, 0, true);
	char floor[32 * 32] = {0};
	IReadFile* floorfile = filesys->createMemoryReadFile(floor, sizeof(char) * 32 * 32, "m2");
	floorNode->loadHeightMapRAW(floorfile);
	//floorNode->setMaterialFlag(EMF_LIGHTING, false);
	floorNode->setScale(vector3df(100, 1, 100));
	floorNode->setPosition(vector3df(-800, 1, -800));
	floorNode->getMaterial(0).EmissiveColor.set(255,10,10,10);
	//floorNode->setVisible(false);

	smgr->addSphereSceneNode(10);

	tool = smgr->addSphereSceneNode(TOOL_R);
	ISceneNodeAnimator* anim = smgr->createRotationAnimator(core::vector3df(0,1,0));
	tool->addAnimator(anim);
	tool->setPosition(vector3df(0, 120, 0));
	tool->setMaterialFlag(EMF_WIREFRAME, true);

	node = smgr->addTerrainSceneNode(0, 0, -1, vector3df(0, 0, 0), vector3df(0, 0, 0), vector3df(1, 1, 1), SColor(255, 255, 255, 255), 0, ETPS_17, 0, true);
	
	
	
	
	for (int i = OFFSET; i < (MATERIAL_SIZE + OFFSET); ++i)
	{
		for (int j = OFFSET; j < (MATERIAL_SIZE + OFFSET); ++j)
		{
			material[i * REAL_SIZE + j] = 100; 
		}
	}

	file = filesys->createMemoryReadFile(material, sizeof(float) * REAL_SIZE * REAL_SIZE, "m1");
	node->loadHeightMapRAW(file, 32, false, true, REAL_SIZE);

	node->getMaterial(0).AmbientColor.set(255,0,0,255);
	//node->getMaterial(0).Shininess = 20.0f;
	
  	//node->setMaterialFlag(EMF_LIGHTING, false);
 	//node->setMaterialFlag(EMF_WIREFRAME, true);
	node->setMaterialFlag(EMF_BACK_FACE_CULLING, false);
	node->setPosition(vector3df(-OFFSET, 0, -OFFSET));


	smgr->addLightSceneNode( 0, core::vector3df(100,300,100), video::SColorf(0.3f,0.3f,0.3f), 300); 

	std::list<vector3df> pathList;
	pathList.push_back(vector3df(30, 100, 30));
	pathList.push_back(vector3df(30, 100, 170));
	pathList.push_back(vector3df(170, 100, 170));
	pathList.push_back(vector3df(170, 100, 30));
	pathList.push_back(vector3df(60, 100, 30));
	pathList.push_back(vector3df(60, 100, 140));
	pathList.push_back(vector3df(140, 100, 140));
	pathList.push_back(vector3df(140, 100, 60));

	std::list<vector3df>::iterator pathIter = pathList.begin();

	int s = 0;


	int lastFPS = -1;

	while(device->run())
	if (device->isWindowActive())
	{
			if (pathIter != pathList.end())
			{
				vector3df endP = *pathIter;
				vector3df noewP = tool->getPosition();

				vector3df vStep;

				if (noewP.X < endP.X)
				{
					vStep.X = STEP;
				}
				if (noewP.X > endP.X)
				{
					vStep.X = -STEP;
				}

				if (noewP.Y < endP.Y)
				{
					vStep.Y = STEP;
				}
				if (noewP.Y > endP.Y)
				{
					vStep.Y = -STEP;
				}

				if (noewP.Z < endP.Z)
				{
					vStep.Z = STEP;
				}
				if (noewP.Z > endP.Z)
				{
					vStep.Z = -STEP;
				}

				tool->setPosition(tool->getPosition() + vStep);
				Cut();

				if (endP.getDistanceFrom(noewP) <= STEP)
				{
					++pathIter;
				}
			}


//  		IMesh* m = node->getMesh();
//  		IMeshBuffer* b = m->getMeshBuffer(0);
//  
//  		u32 c1 = m->getMeshBufferCount();
//  
//  		u32 c2 = b->getVertexCount();
//  
//  		void* v = b->getVertices();
//  
//   		for (int i = 0; i < 30; ++i)
//   		{
//   			for (int j = 0; j < 30; ++j)
//   			{
//  				S3DVertex2TCoords* tmpv = (static_cast<S3DVertex2TCoords*>(v) + (i + s + 10) * 128 + (j + s + 10));
//  
//   				tmpv->Pos.Y = 1000;
//   			}
//   		}
//   
//   		s = (s + 1) % 50 + 10;
//   
//   		for (int i = 0; i < 30; ++i)
//   		{
//   			for (int j = 0; j < 30; ++j)
//   			{
//  				S3DVertex2TCoords* tmpv = (static_cast<S3DVertex2TCoords*>(v) + (i + s + 10) * 128 + (j + s + 10));
//  
//  				tmpv->Pos.Y = 800;
//   			}
//   		}
//  		node->setPosition(node->getPosition());


		driver->beginScene(true, true, 0 );

		smgr->drawAll();
		env->drawAll();


// 		for (int i = 0; i < 30; ++i)
// 		{
// 			for (int j = 0; j < 30; ++j)
// 			{
// 				material[(i + s + 10) * 128 + (j + s + 10)] = 1000;
// 			}
// 		}
// 
// 		s = (s + 1) % 50 + 10;
// 
// 		for (int i = 0; i < 30; ++i)
// 		{
// 			for (int j = 0; j < 30; ++j)
// 			{
// 				material[(i + s + 10) * 128 + (j + s + 10)] = 800;
// 			}
// 		}
// 
// 		file->read(material, sizeof(float) * 128 * 128);
// 		file->seek(0);
// 		node->loadHeightMapRAW(file, 32, false, true, 128);
// 
// 		node->setMaterialFlag(EMF_LIGHTING, false);
// 		node->setMaterialFlag(EMF_WIREFRAME, true);
// 		node->setMaterialFlag(EMF_BACK_FACE_CULLING, false);
// 		node->setMaterialFlag(EMF_FRONT_FACE_CULLING, false);

		


		driver->endScene();

		// display frames per second in window title
		int fps = driver->getFPS();
		if (lastFPS != fps)
		{
			core::stringw str = L"Terrain Renderer - Irrlicht Engine [";
			str += driver->getName();
			str += "] FPS:";
			str += fps;
			// Also print terrain height of current camera position
			// We can use camera position because terrain is located at coordinate origin

			device->setWindowCaption(str.c_str());
			lastFPS = fps;
		}
	}

	device->drop();

	return 0;
}
Example #21
0
bool
sTileset::Import_TST(const char* filename, IFileSystem& fs)
{
  // TST file format created by Christoper B. Matthews for the RPG Toolkit Development System

  IFile* file = fs.Open(filename, IFileSystem::read);
  if (file == NULL)
    return false;

  // read header
  word version;
  word numtiles;
  word detail;
  file->Read(&version,  2);
  file->Read(&numtiles, 2);
  file->Read(&detail,   2);

  // check header for errors
  // only support details 2, 4, 6
  if (version != 20 && (detail == 2 || detail == 4 || detail == 6))
  {
    file->Close();
    return false;
  }

  // allocate new tiles
  m_Tiles.clear();
  m_Tiles.resize(numtiles);

  // read them from file
  for (int i = 0; i < m_Tiles.size(); i++)
  {
    sTile& tile = m_Tiles[i];
    switch (detail)
    {
      case 2: // 16x16, 24-bit color
      {
        for (int ix = 0; ix < 16; ix++)
          for (int iy = 0; iy < 16; iy++)
          {
            RGB rgb;
            file->Read(&rgb, 3);
            byte alpha = 255;
            if (rgb.red == 0 && rgb.green == 1 && rgb.blue == 2)
              alpha = 0;
            tile.GetPixels()[iy * 16 + ix].red   = rgb.red;
            tile.GetPixels()[iy * 16 + ix].green = rgb.green;
            tile.GetPixels()[iy * 16 + ix].blue  = rgb.blue;
            tile.GetPixels()[iy * 16 + ix].alpha = alpha;
          }
        break;
      }

      case 4: // 16x16, 8-bit color
      case 6: // 16x16, 4-bit color
              // these two are effectively the same format
      {
        for (int ix = 0; ix < 16; ix++)
          for (int iy = 0; iy < 16; iy++)
          {
            byte b;
            file->Read(&b, 1);
            RGB rgb = dos_palette[b];
            byte alpha = 255;
            if (b == 255)
              alpha = 0;

            tile.GetPixels()[iy * 16 + ix].red   = rgb.red;
            tile.GetPixels()[iy * 16 + ix].green = rgb.green;
            tile.GetPixels()[iy * 16 + ix].blue  = rgb.blue;
            tile.GetPixels()[iy * 16 + ix].alpha = alpha;
          }

        break;
      }
    }
  }

  file->Close();
  return true;
}
Example #22
0
bool CMeshLoader::Load(const wchar* path, bool ignore_animation_data/*=false*/)
{
	if (m_bLoaded)
	{
		Unload();	
		m_bLoaded = false;
	}
	IFileSystem* pFS = CEngine::instance()->mFilesystem();

	unsigned int ltim = GetTickCount();

	// open file
	wchar fspath[P3DMAX_PATH];
	wsprintf(fspath, P3DMAX_PATH-1, _W("models/%s.rmesh"), path);
	FSFILE* fp = pFS->Open(fspath, _W("rb"));
	if (!fp)
	{
		CON(MSG_ERR, _W("MeshLoader: Can't find mesh file '%s'!"), fspath);
		return false;
	}
	if (fp->nLen<sizeof(sRMHeader))
	{
		CON(MSG_ERR, _W("MeshLoader: Mesh file '%s' is corrupted!"), fspath);
		pFS->Close(fp);
		return false;
	}

	// load and check header
	m_rhead = new sRMHeader();
	pFS->Read(m_rhead, sizeof(sRMHeader), 1, fp);
	if (m_rhead->magic[0]!='R' || m_rhead->magic[1]!='M')
	{
		CON(MSG_ERR, _W("MeshLoader: File '%s' is not valid RMesh!"), fspath);
		pFS->Close(fp);
		return false;
	}
	if (m_rhead->major!=RM_MAJOR)
	{
		CON(MSG_ERR, _W("MeshLoader: Mesh '%s' is version %d, but engine can load only %d!"), fspath, m_rhead->major, RM_MAJOR);
		pFS->Close(fp);
		return false;
	}
	if (m_rhead->minor!=RM_MINOR)
	{
		CON(MSG_DBG, _W("MeshLoader: Minor version warning. Mesh '%s' is minor version %d, engine can load %d."), fspath, m_rhead->minor, RM_MINOR);
	}

	m_bLoaded=true;

	// LOAD INFO ---------------------------------------------------
	m_rinfo = new sRMInfo();
	pFS->Seek(fp, m_rhead->contents[RM_FILE_INFO].offset, SEEK_SET);
	pFS->Read(m_rinfo, sizeof(sRMInfo), 1, fp);

	// LOAD SUBSETS ---------------------------------------------------
	m_nSubsets = m_rhead->contents[RM_SUBSETS].length/sizeof(sRMSubset);
	m_rsubsets = new sRMSubset[m_nSubsets];
	pFS->Seek(fp, m_rhead->contents[RM_SUBSETS].offset, SEEK_SET);
	pFS->Read(m_rsubsets, sizeof(sRMSubset), m_nSubsets, fp);

	// LOAD VERTICES ---------------------------------------------------
	m_nVerts = m_rhead->contents[RM_VERTICES].length/sizeof(sRMVertex);
	m_rverts = new sRMVertex[m_nVerts];
	pFS->Seek(fp, m_rhead->contents[RM_VERTICES].offset, SEEK_SET);
	pFS->Read(m_rverts, sizeof(sRMVertex), m_nVerts, fp);

	// LOAD INDICES ---------------------------------------------------
	m_nInds = m_rhead->contents[RM_INDICES].length/sizeof(sRMIndex);
	m_rinds = new sRMIndex[m_nInds];
	pFS->Seek(fp, m_rhead->contents[RM_INDICES].offset, SEEK_SET);
	pFS->Read(m_rinds, sizeof(sRMIndex), m_nInds, fp);

	// MAKE FACE GROUPS -----------------------------------------------
	m_faceGroups = new unsigned int[m_nInds/3];
	memset(m_faceGroups, 0, sizeof(unsigned int)*m_nInds/3);
	for (unsigned int s=0; s<m_nSubsets; s++)
	{
		// find faces which belongs to this subset
		unsigned int beginFace = m_rsubsets[s].firstindex/3;
		unsigned int endFace = (m_rsubsets[s].firstindex+m_rsubsets[s].numindices)/3;
		
		// assign face groups to this subset
		for (unsigned int f=beginFace; f<endFace; f++) m_faceGroups[f]=s;
	}

	// IF THIS FILE HAS ANIMATION AND IT IS LAODED MAKE SURE TO SET m_bAnimated TO TRUE
	m_bAnimated = false;
	if (!m_rinfo->idontimportanim)
	{
		// check if file contain animated content
		// TODO:
	}

	// close file
	pFS->Close(fp);

	ltim = GetTickCount() - ltim;
	if (ltim<1000)
		CON(MSG_INFO, _W("MeshLoader: Mesh '%s' loaded. Loading took %d miliseconds."), path, ltim);
	else
		CON(MSG_INFO, _W("MeshLoader: Mesh '%s' loaded. Loading took %d seconds."), path, ltim/1000);
	return true;
}
Example #23
0
bool
sTileset::Import_VSP(const char* filename, IFileSystem& fs)
{
  IFile* file = fs.Open(filename, IFileSystem::read);
  if (file == NULL)
    return false;

  word version;
  RGB palette[256];
  word numtiles;

  file->Read(&version,  2);
  file->Read(palette,   3 * 256);
  file->Read(&numtiles, 2);

  m_Tiles.clear();
  m_Tiles.resize(numtiles);

  // decode the file
  if (version == 2)
  {
    for (int i = 0; i < numtiles; i++)
    {
      byte tile[256];

      file->Read(tile, 256);
      for (int x = 0; x < 16; x++)
        for (int y = 0; y < 16; y++)
        {
          RGBA color;
          byte c = tile[y * 16 + x];
          if (c == 0)
          {
            color.red = 0;
            color.green = 0;
            color.blue = 0;
            color.alpha = 0;
          }
          else
          {
            color.red   = (byte)(palette[c].red   * 4);
            color.green = (byte)(palette[c].green * 4);
            color.blue  = (byte)(palette[c].blue  * 4);
            color.alpha = 255;
          }

          m_Tiles[i].GetPixels()[y * 16 + x] = color;
        }
    }
  }
  else
  {
    // for that wierd thing aen never told me in the vsp code
    dword dw;
    file->Read(&dw, 4);

    // create a temporary buffer while setting up the decoding stuff...
    byte* buffer = (byte*)malloc(numtiles * 256);
    int len = numtiles * 256;
    int counter = 0;

    //start decoding!
    while (counter < len)
    {
      byte c;
      file->Read(&c, 1);

      // if the c was 255 then it's a compressed value
      if (c == 255)
      {
        byte run, color;
        file->Read(&run, 1);
        file->Read(&color, 1);

        for (int i = 0; i < run; i++)
        {
          buffer[counter] = color;
          counter++;
        }
      }
      else  // it's a normal value
      {
        buffer[counter] = c;
        counter++;
      }
    }

    // now, tranfer the decoded stuff into the tiles' data structure
    for (int i = 0; i < numtiles; i++)
      for (int j = 0; j < 256; j++)
      {
        if (buffer[i * 256 + j] == 0)
        {
          m_Tiles[i].GetPixels()[j].red   = 0;
          m_Tiles[i].GetPixels()[j].green = 0;
          m_Tiles[i].GetPixels()[j].blue  = 0;
          m_Tiles[i].GetPixels()[j].alpha = 0;
        }
        else
        {
          m_Tiles[i].GetPixels()[j].red   = (palette[buffer[i * 256 + j]].red)   * 4;
          m_Tiles[i].GetPixels()[j].green = (palette[buffer[i * 256 + j]].green) * 4;
          m_Tiles[i].GetPixels()[j].blue  = (palette[buffer[i * 256 + j]].blue)  * 4;
          m_Tiles[i].GetPixels()[j].alpha = 255;
        }
      }
  }

  file->Close();
  return true;
}
Example #24
0
	bool CShaderHLSL::Create(P3D::sShaderDesc &desc)
	{
		const char *pData;
		ULONG fsize;
		IFileSystem* pFS = CRenderer::mEngine()->mFilesystem();
		wchar path[P3DMAX_PATH];
		wsprintf(path, P3DMAX_PATH-1, _W("shaders/%s.rshader"), desc.ShaderFile.Get());
		FSFILE *fp = pFS->Load(path, (BYTE *&)pData, fsize, true);
		if (!fp)
		{
			CON(MSG_ERR, _W("Can't open %s.hlsl shader file from data/shaders directory!"), desc.ShaderFile.Get());
			return false;
		}

		ID3D10Blob *pShaderBlob = NULL;
		ID3D10Blob *pErrors = NULL;
		UINT flags = D3D10_SHADER_DEBUG;  //D3D10_SHADER_OPTIMIZATION_LEVEL3

		char profile[128];
		switch(desc.ShaderType)
		{
		case SHADERTYPE_VERTEX_SHADER:
			strcpy(profile, D3D10GetVertexShaderProfile(g_pD3ddev));
			break;
		case SHADERTYPE_GEOMETRY_SHADER:
			strcpy(profile, D3D10GetGeometryShaderProfile(g_pD3ddev));
			break;
		case SHADERTYPE_PIXEL_SHADER:
			strcpy(profile, D3D10GetPixelShaderProfile(g_pD3ddev));
			break;
		default:
			CON(MSG_ERR, _W("Chader creation failed. No apropriate ShaderType given."));
			return false;
		}

		CIncludeHandler includeHandler;
		
		D3D10_SHADER_MACRO Shader_Macros[] = 
		{
			{ "DX10", NULL },
			{ "SM4", NULL },
			NULL
		};

		if(!CheckHRResult(D3DX10CompileFromMemory(
			pData, 
			fsize, 
			NULL, 
			Shader_Macros, 
			&includeHandler, 
			_W2A(desc.EntryFunction.Get()), 
			profile, 
			flags,
			0,
			NULL,
			&pShaderBlob, 
			&pErrors,
			NULL
			)))
		{
			if(pErrors) CON(MSG_ERR, _W("%s"), _A2W((char*)pErrors->GetBufferPointer()));
			else CON(MSG_ERR, _W("Error description not given"));
			CON(MSG_ERR, _W("Shader %s could not be compiled"), desc.ShaderFile.Get());
			SAFE_RELEASE(pErrors);
			return false;
		}

		pFS->UnLoad(fp, (BYTE *)pData);

		//save to cache
		fp = pFS->Open(_W("cache/shaders/hlsl"), _W("wb"));
		const char* cs = (const char*)pShaderBlob->GetBufferPointer();
		pFS->Write(cs, 1, pShaderBlob->GetBufferSize(), fp);
		pFS->Close(fp);

		bool shaderCreated = false;
		switch(desc.ShaderType)
		{
		case SHADERTYPE_VERTEX_SHADER:
			shaderCreated = CheckHRResult(g_pD3ddev->CreateVertexShader(pShaderBlob->GetBufferPointer(), pShaderBlob->GetBufferSize(), &m_pVS));
			break;
		case SHADERTYPE_GEOMETRY_SHADER:
			shaderCreated = CheckHRResult(g_pD3ddev->CreateGeometryShader(pShaderBlob->GetBufferPointer(), pShaderBlob->GetBufferSize(), &m_pGS));
			break;
		case SHADERTYPE_PIXEL_SHADER:
			shaderCreated = CheckHRResult(g_pD3ddev->CreatePixelShader(pShaderBlob->GetBufferPointer(), pShaderBlob->GetBufferSize(), &m_pPS));
			break;
		}
		
		if(!shaderCreated)
		{
			CON(MSG_ERR, _W("Shader creation error"));
			return false;
		}

		//if(!CheckHRResult(D3DReflect((DWORD*)pShaderBlob->GetBufferPointer(), pShaderBlob->GetBufferSize(), __uuidof(ID3D10ShaderReflection), &m_pReflection)))
		if(!CheckHRResult(D3D10ReflectShader(pShaderBlob->GetBufferPointer(), pShaderBlob->GetBufferSize(), &m_pReflection)))
		{
			CON(MSG_ERR, _W("Could not create a Shader reflection"));
			return false;
		}
		//HRESULT D3DReflect(LPCVOID pSrcData, SIZE_T SrcDataSize, REFIID pInterface,	void **ppReflector);
		D3D10_SHADER_DESC shDesc;
		m_pReflection->GetDesc(&shDesc);
		m_numResources = shDesc.BoundResources; //not sure about this

		if(desc.ShaderType == SHADERTYPE_VERTEX_SHADER)
			m_pVertDecl = new CVertexDeclaration(CRenderer::cGraphicsManager()->GetVertexDescByID(desc.VertexDescID), pShaderBlob);
		
		SAFE_RELEASE(pShaderBlob);

		m_desc = desc;

		CON(MSG_INFO, _W("Shader '%s' created"), desc.ShaderFile);
		
		return true;
	}
void PrintPlayerClassStats()
{
	IFileSystem *pFileSys = filesystem;

	FileHandle_t hFile = pFileSys->Open( "class_stats.txt", "wt", "LOGDIR" );
	if ( hFile == FILESYSTEM_INVALID_HANDLE )
		return;


	pFileSys->FPrintf( hFile, "Class\tPlayer Time (minutes)\tAvg Engagement Dist\t(OLD) Engagement Dist\n" );
	for ( int i=TFCLASS_UNDECIDED+1; i < STATS_NUM_GROUPS; i++ )
	{
		CPlayerClassStats *pStats = &g_PlayerClassStats[i];


		// Figure out the average engagement distance across all classes.
		int j;
		double flAvgEngagementDist = 0;
		int nTotalEngagements = 0;
		double flTotalEngagementDist = 0;

		double flTotalNormalizedEngagementDist = 0;
		int nTotalNormalizedEngagements = 0;

		for ( j=TFCLASS_UNDECIDED+1; j < STATS_NUM_GROUPS; j++ )
		{
			CInterClassStats *pInter = &g_PlayerClassStats[i].m_InterClassStats[j];
			
			nTotalEngagements += pInter->m_nEngagements;
			flTotalEngagementDist += pInter->m_flTotalEngagementDist;

			nTotalNormalizedEngagements += pInter->m_nNormalizedEngagements;
			flTotalNormalizedEngagementDist += pInter->m_flTotalNormalizedEngagementDist;
		}
		flAvgEngagementDist = nTotalEngagements ? ( flTotalEngagementDist / nTotalEngagements ) : 0;
		double flAvgNormalizedEngagementDist = nTotalNormalizedEngagements ? (flTotalNormalizedEngagementDist / nTotalNormalizedEngagements) : 0;
		
		
		pFileSys->FPrintf( hFile, "%s",		GetGroupNameFor( i ) );
		pFileSys->FPrintf( hFile, "\t%.1f", (pStats->m_flPlayerTime / 60.0f) );
		pFileSys->FPrintf( hFile, "\t%d",	(int)flAvgNormalizedEngagementDist );
		pFileSys->FPrintf( hFile, "\t%d",	(int)flAvgEngagementDist );
		pFileSys->FPrintf( hFile, "\n" );
	}

	pFileSys->FPrintf( hFile, "\n" );
	pFileSys->FPrintf( hFile, "\n" );


	pFileSys->FPrintf( hFile, "Class\tTarget Class\tTotal Damage\tKills\tAvg Engagement Dist\t(OLD) Engagement Dist\n" );
	
	for ( i=TFCLASS_UNDECIDED+1; i < STATS_NUM_GROUPS; i++ )
	{
		CPlayerClassStats *pStats = &g_PlayerClassStats[i];

		// Print the inter-class stats.
		for ( int j=TFCLASS_UNDECIDED+1; j < STATS_NUM_GROUPS; j++ )
		{
			CInterClassStats *pInter = &pStats->m_InterClassStats[j];

			pFileSys->FPrintf( hFile, "%s", GetGroupNameFor( i ) );
			pFileSys->FPrintf( hFile, "\t%s", GetGroupNameFor( j ) );
			pFileSys->FPrintf( hFile, "\t%d", (int)pInter->m_flTotalDamageInflicted );
			pFileSys->FPrintf( hFile, "\t%d", pInter->m_nKills );
			pFileSys->FPrintf( hFile, "\t%d", (int)(pInter->m_nNormalizedEngagements ? (pInter->m_flTotalNormalizedEngagementDist / pInter->m_nNormalizedEngagements) : 0) );
			pFileSys->FPrintf( hFile, "\t%d", (int)(pInter->m_nEngagements ? (pInter->m_flTotalEngagementDist / pInter->m_nEngagements) : 0) );
			pFileSys->FPrintf( hFile, "\n" );
		}
	}

	pFileSys->Close( hFile );
}
Example #26
0
// ------------------------------------------------
bool CTextureLoader::Load(const wchar* path)
{
	IFileSystem *fs = CRenderer::mEngine()->mFilesystem();

	Unload();
	//memset(&m_info, 0, sizeof(sRTInfo));

	// make physical FS path
	wchar physPath[512];
	wsprintf(physPath, 511, _W("textures/%s.rtex"), path);
	for (unsigned int i=0; i<wstrlen(physPath); i++)
		if (physPath[i]==',') physPath[i]='/';

	FSFILE* fp;
	fp =  fs->Open(physPath, _W("rb"));
	if (!fp)
	{
		return false;
	}

	m_dataLen = fp->nLen;

	if (m_dataLen < sizeof(sRTHeader))
	{
		fs->Close(fp);
		return false;
	}

	// read header
	sRTHeader head;
	fs->Read(&head, 1, sizeof(sRTHeader), fp);

	// check header
	if (head.magic[0]!='R' || head.magic[1]!='T')
	{
		CON(MSG_ERR, _W("Texture %s is not valid rtex!"), path);
		fs->Close(fp);
		return false;
	}

	// load texture info
	fs->Seek(fp, head.contents[RT_FILE_INFO].offset, SEEK_SET);
	fs->Read(&m_info, 1, sizeof(sRTInfo), fp);

	// load texture data
	unsigned long rawDataLen = fp->nLen-head.contents[RT_IMAGE_SUBSET].offset-head.contents[RT_IMAGE_SUBSET].length;
	m_data = new BYTE[rawDataLen];
	fs->Seek(fp, head.contents[RT_IMAGE_SUBSET].offset+head.contents[RT_IMAGE_SUBSET].length, SEEK_SET);
	fs->Read(m_data, 1, rawDataLen, fp);

	m_bLoaded=true;

	// load all subsets
	fs->Seek(fp, head.contents[RT_IMAGE_SUBSET].offset, SEEK_SET);
	unsigned int numSubs = head.contents[RT_IMAGE_SUBSET].length / sizeof(sRTImageSubset);

	for (unsigned int s = 0; s < numSubs; s++)
	{
		sImageData* ida = new sImageData();
		fs->Read(&ida->subset, 1, sizeof(sRTImageSubset), fp);
		ida->size = ida->subset.len;
		ida->pData = &m_data[ida->subset.offset];
		m_subs.push_back(ida);
	}

	fs->Close(fp);

	int i = 0; // debug

	return true;
}
Example #27
0
bool
sMap::Save(const char* filename, IFileSystem& fs)
{
  // do some preliminary checking...
  // the start layer should not have parallax
  m_Layers[m_StartLayer].EnableParallax(false);

  IFile* file = fs.Open(filename, IFileSystem::write);
  if (file == NULL)
    return false;

  // write the map header
  MAP_HEADER header;
  memset(&header, 0, sizeof(header));
  memcpy(header.signature, ".rmp", 4);
  header.version        = 1;
  header.num_layers     = m_Layers.size();
  header.num_entities   = m_Entities.size();
  header.startx         = m_StartX;
  header.starty         = m_StartY;
  header.startlayer     = m_StartLayer;
  header.startdirection = m_StartDirection;
  header.num_strings    = 9;
  file->Write(&header, sizeof(header));

  // write the strings
  WriteMapString(file, "");  // OBSOLETE
  WriteMapString(file, m_MusicFile.c_str());
  WriteMapString(file, "");  // OBSOLETE
  WriteMapString(file, m_EntryScript.c_str());
  WriteMapString(file, m_ExitScript.c_str());
  WriteMapString(file, m_EdgeScripts[0].c_str());
  WriteMapString(file, m_EdgeScripts[1].c_str());
  WriteMapString(file, m_EdgeScripts[2].c_str());
  WriteMapString(file, m_EdgeScripts[3].c_str());
 
  // write layers
  for (int i = 0; i < m_Layers.size(); i++)
  {
    const sLayer& layer = m_Layers[i];
    const sObstructionMap& obstructions = layer.GetObstructionMap();

    // write the header
    LAYER_HEADER lh;
    memset(&lh, 0, sizeof(lh));
    lh.width        = m_Layers[i].GetWidth();
    lh.height       = m_Layers[i].GetHeight();
    lh.flags        = (m_Layers[i].IsVisible() ? 0 : 1) | (m_Layers[i].HasParallax() ? 2 : 0);
    lh.parallax_x   = m_Layers[i].GetXParallax();
    lh.parallax_y   = m_Layers[i].GetYParallax();
    lh.scrolling_x  = m_Layers[i].GetXScrolling();
    lh.scrolling_y  = m_Layers[i].GetYScrolling();
    lh.num_segments = obstructions.GetNumSegments();
    lh.reflective   = (m_Layers[i].IsReflective() ? 1 : 0);
    file->Write(&lh, sizeof(lh));

    // write the layer name
    WriteMapString(file, m_Layers[i].GetName());

    // write the layer data
    for (int iy = 0; iy < m_Layers[i].GetHeight(); iy++)
      for (int ix = 0; ix < m_Layers[i].GetWidth(); ix++)
      {
        word w = m_Layers[i].GetTile(ix, iy);
        file->Write(&w, 2);
      }

    // write the obstruction map
    for (int i = 0; i < obstructions.GetNumSegments(); i++) {
      const sObstructionMap::Segment& s = obstructions.GetSegment(i);

      dword x1 = s.x1;
      dword y1 = s.y1;
      dword x2 = s.x2;
      dword y2 = s.y2;

      file->Write(&x1, sizeof(dword));
      file->Write(&y1, sizeof(dword));
      file->Write(&x2, sizeof(dword));
      file->Write(&y2, sizeof(dword));
    }

  } // end for layer

  // write entities
  for (int i = 0; i < m_Entities.size(); i++)
  {
    // write the header
    ENTITY_HEADER eh;
    memset(&eh, 0, sizeof(eh));
    eh.mapx  = m_Entities[i]->x;
    eh.mapy  = m_Entities[i]->y;
    eh.layer = m_Entities[i]->layer;
    switch (m_Entities[i]->GetEntityType())
    {
      case sEntity::PERSON:  eh.type = 1; break;
      case sEntity::TRIGGER: eh.type = 2; break;
    }
    file->Write(&eh, sizeof(eh));

    // write the entity data
    switch (m_Entities[i]->GetEntityType())
    {
      case sEntity::PERSON:
      {
        sPersonEntity* person = (sPersonEntity*)m_Entities[i];

        WriteMapString(file, person->name.c_str());
        WriteMapString(file, person->spriteset.c_str());

        WriteMapWord(file, 5);  // four scripts
        
        // scripts
        WriteMapString(file, person->script_create.c_str());
        WriteMapString(file, person->script_destroy.c_str());
        WriteMapString(file, person->script_activate_touch.c_str());
        WriteMapString(file, person->script_activate_talk.c_str());
        WriteMapString(file, person->script_generate_commands.c_str());

        // reserved
        for (int i = 0; i < 16; i++) {
          WriteMapByte(file, 0);
        }

        break;
      }

      case sEntity::TRIGGER:
      {
        sTriggerEntity* trigger = (sTriggerEntity*)m_Entities[i];
        WriteMapString(file, trigger->script.c_str());
        break;
      }

    } // end switch entity type
  } // end for entity

  // write the zones
  for (int i = 0; i < m_Zones.size(); i++)
  {
    ZONE_HEADER zh;

    memset(&zh, 0, sizeof(zh));
    zh.x1 = m_Zones[i].x1;
    zh.y1 = m_Zones[i].y1;
    zh.x2 = m_Zones[i].x2;
    zh.y2 = m_Zones[i].y2;
    zh.layer = m_Zones[i].layer;
    zh.reactivate_in_num_steps = m_Zones[i].reactivate_in_num_steps;

    file->Write(&zh, sizeof(zh));
    WriteMapString(file, m_Zones[i].script.c_str());
  } // end for zones

  // save the tileset
  if (!m_Tileset.SaveToFile(file)) {
    file->Close();
    return false;
  }

  file->Close();
  return true;
}
Example #28
0
void        ModuleManager::scanModuleDir()
{
    if (RootConfig::isSet("ModulesDir") == false)
    {
        Logger::getInstance() << Logger::Warning << "No modules dir specified. No module will be loaded" << Logger::Flush;
        return ;
    }
    //Retreiving modules in ModulesDir
    IFileSystem* fs = new FileSystem(RootConfig::getParamChar("ModulesDir"));
#ifndef _WIN32
    std::list<IFile*>* files = fs->getFileList("so");
#else
	std::list<IFile*>* files = fs->getFileList("dll");
#endif // !_WIN32
    if (files != NULL)
    {
        //Creating a new modules list
        ModuleStuff     newStuff;
        std::list<RefCounter<zAPI::IModuleInfo*>*>* newList = new std::list<RefCounter<zAPI::IModuleInfo*>*>[zAPI::IModule::NumberOfHooks];
        newStuff.list = NULL;
        newStuff.hooks = newList;
        //duplicating old list, to apply changes from the old one to the new one
        if (this->_modules.size() > 0)
        {
            for (int i = 0; i < zAPI::IModule::NumberOfHooks; ++i)
                newList[i] = this->_modules.back().ptr.hooks[i];
        }
        //flag to see if some changes occured.
        bool    firstChange = true;

        //files list iterators
        std::list<IFile*>::iterator it;
        std::list<IFile*>::iterator ite = files->end();

        //modules instance iterators

        std::list<RefCounter<zAPI::IModuleInfo*> >::iterator mIt = this->_moduleInstances.begin();
        std::list<RefCounter<zAPI::IModuleInfo*> >::iterator mIte = this->_moduleInstances.end();
        //First we look if some modules doesn't exists anymore.
        for (; mIt != mIte; ++mIt)
        {
            for (it = files->begin(); it != ite; ++it)
            {
                if ((*it)->getFullFileName() == (*mIt).ptr->getFileName())
                    break;
            }
            if (it == ite) //module wasn't in dir anymore : unloading
            {
                if (firstChange)
                {
                    this->_modules.push_back(newStuff);
                    this->_modules.back().count = 0;
                    firstChange = false;
                }
                Logger::getInstance() << Logger::Info << (*mIt).ptr->getFileName() << " is missing from ModulesDir. Unloading module." << Logger::Flush;
                this->unload((*mIt).ptr->getFileName());
                if ((*mIt).count == 0)
                {
                    mIt = this->_moduleInstances.erase(mIt);
                    mIte = this->_moduleInstances.end();
                }
            }
        }
        //Then we add new modules
        it = files->begin();
        for (; it != ite; ++it)
        {
            if (this->isLoaded((*it)->getFullFileName()) == false)
            {
                if (firstChange)
                {
                    this->_modules.push_back(newStuff);
                    this->_modules.back().count = 0;
                    firstChange = false;
                }
                this->load((*it)->getFullFileName());
            }
        }
        if (firstChange == true)
            delete[] newList;
        else
            this->createModuleStuff();
    }
    delete fs;
}
Example #29
0
    //-------------------------------------------------------------------------
    //                                   i n i t
    //-------------------------------------------------------------------------
    int CApplication::init()
    {
        SIrrlichtCreationParameters cp;
        static SKeyMap keyMap[5];
        keyMap[0].Action = EKA_MOVE_FORWARD;
        keyMap[0].KeyCode = KEY_KEY_W;
        keyMap[1].Action = EKA_STRAFE_LEFT;
        keyMap[1].KeyCode = KEY_KEY_A;
        keyMap[2].Action = EKA_MOVE_BACKWARD;
        keyMap[2].KeyCode = KEY_KEY_S;
        keyMap[3].Action = EKA_STRAFE_RIGHT;
        keyMap[3].KeyCode = KEY_KEY_D;
        keyMap[4].Action = EKA_JUMP_UP;
        keyMap[4].KeyCode = KEY_SPACE;

        int result=0;
        stringc msg;


        // use null device for early file system access
        IrrlichtDevice* m_nullDevice = createDevice(EDT_NULL);
        IFileSystem* fileSystem = m_nullDevice->getFileSystem();

        m_currentDirectory = fileSystem->getWorkingDirectory();
        m_currentDirectory = fileSystem->flattenFilename(m_currentDirectory);
        if(m_argv)
        {
            m_appExecutable = m_argv[0];
        }
        else
        {
            m_appExecutable = "irrlicht.exe";
        }


        stringc appBaseName;
        appBaseName = fileSystem->getAbsolutePath(m_appExecutable);
        appBaseName = fileSystem->getFileBasename(appBaseName, false);

        //
        // create log writer
        //
        m_logName = appBaseName;
        m_logName += ".log";

        m_logFile = fileSystem->createAndWriteFile(m_logName);

        msg = "Created log file: ";
        msg += m_logName;
        logMessage(msg);

        //
        // configuration system
        //
        // locate the data directory - underneath our executable or outside of it.
        stringc temp("data/");
        if(!fileSystem->existFile(temp))
        {
            temp = "../data/";
            // todo - look for "data.zip"...
        }
        m_dataRoot = fileSystem->getAbsolutePath(temp);
        m_configName = m_dataRoot;
        m_configName += "/cfg/";
        m_configName += appBaseName;
        m_configName += ".xml";


        if(!fileSystem->existFile(m_configName))
        {
            // not in data/cfg or ../data/cfg so look in the working directory.
            m_configName = appBaseName;
            m_configName += ".xml";
            if(!fileSystem->existFile(m_configName))
            {
                return -1;
            }
        }

        // load the config file
        m_config = new CXMLConfig();
        if(!m_config->load(m_configName))
        {
            return -1;
        }

        // setup the device based on config settings
        stringc sdriver = m_config->getString("driver","video","EDT_OPENGL");
        cp.DriverType = EDT_OPENGL;
        if(sdriver == "EDT_DIRECT3D9")
            cp.DriverType = EDT_DIRECT3D9;        
        cp.WindowSize = m_config->getDimension("resolution","video",dimension2di(800, 600));
        cp.Bits = m_config->getInt("colordepth","video",32);
        cp.Fullscreen = m_config->getBool("fullscreen","video",false);
        cp.Vsync = m_config->getBool("vsync","video",true);
        cp.Stencilbuffer = m_config->getBool("stencilbuffer","video",false);
        cp.AntiAlias = m_config->getInt("antialias","video",0);
        cp.EventReceiver = this;
        cp.WindowId = 0;

        m_device =  createDeviceEx(cp);
        if(!m_device)
            return -1;

        m_fileSystem = m_device->getFileSystem();
        m_videoDriver = m_device->getVideoDriver();
        m_sceneManager = m_device->getSceneManager();
        m_gui = m_device->getGUIEnvironment();

        m_device->getCursorControl()->setVisible(m_config->getBool("HWCursorVisible","video",true));
        m_device->setWindowCaption(stringw(m_title).c_str());


        //
        // add configured file systems
        //
        if(_initFileSystems())
            return -1;

        //
        // set up the default font
        //        
        stringc fontFolder = "fnt/";
        stringc defFonts = fontFolder + "defaults.zip";
        if(m_fileSystem->existFile(defFonts.c_str()))
        {
            m_fileSystem->addZipFileArchive(defFonts.c_str());
            m_defaultFont = m_gui->getFont("tdeffont.xml");
            if(m_defaultFont)
            {
                m_defaultFont->grab();
                m_gui->getSkin()->setFont(m_defaultFont);
            }
            m_monoFont = m_gui->getFont("monospace.xml");
            if(m_monoFont)
            {
                m_monoFont->grab();
            }
        }

        m_world = m_sceneManager->createMetaTriangleSelector();

        // camera setup
        f32 rotateSpeed = m_config->getFloat("rotateSpeed","options",100.f);
        m_orgMoveSpeed = m_config->getFloat("moveSpeed","options",0.001f);
        f32 jumpSpeed = m_config->getFloat("jumpSpeed","options",0.05f);
        m_camera = m_sceneManager->addCameraSceneNodeFPS(0, rotateSpeed, m_orgMoveSpeed, -1,keyMap,5,true, jumpSpeed);

        vector3df v = m_config->getVector3("campos","options");
        m_camera->setPosition(v);

        v = m_config->getVector3("camtarget","options");
        m_camera->setTarget(v);

        bool collisionEnabled = m_config->getBool("collision","options");
        if(collisionEnabled)
        {
            vector3df gravity,ellipsoid;
            gravity = m_config->getVector3("gravity","options",vector3df(0,-0.1f,0));
            ellipsoid = m_config->getVector3("ellipsoid","options",vector3df(2,5,2));
            m_collisionResponse = m_sceneManager->createCollisionResponseAnimator(m_world,m_camera,
                ellipsoid, gravity);
            m_camera->addAnimator(m_collisionResponse);
        }
        
        // debug & help panels setup
        m_debugPanel = new gui::CGUITextPanel(m_gui, "debugPanel", rectf(0.25f,0.005f,0.75f,0.05f));
        m_debugPanel->addItem("Node: Pos(x,y,z) Hpr(x,y,z) Dir(x,y,z)", EGUIA_CENTER);
        m_debugPanel->addItem("Frame: Avg(0.0) Min(0.0) Max(0.0)", EGUIA_CENTER);
        m_debugPanel->setVisible(true);

        m_helpPanel = new gui::CGUITextPanel(m_gui, "helpPanel", rectf(0.005f,0.005f,0.245f,0.05f));
        m_helpPanel->addItem(" wasd - Movement");
        m_helpPanel->addItem("   F1 - Toggle Help");
        m_helpPanel->addItem("   F2 - Toggle Debug");

        createScene();

        return result;
    }
Example #30
0
bool
sMap::Import_VergeMAP(const char* filename, const char* tilesetFilename, IFileSystem& fs)
{
  m_MusicFile   = "";
  m_EntryScript = "";
  m_ExitScript  = "";
  m_Layers.clear();
  m_Entities.clear();

  IFile* file = fs.Open(filename, IFileSystem::read);
  if (file == NULL) 
    return false;

  // check for v1 maps (ver 4) and v2 maps (ver 5)
  char signature[6];
  file->Read(signature, 6);
  file->Seek(0);

  bool success = false;

  if (signature[0] == 4)
  {
    V1MAP_HEADER header;
    file->Read(&header, sizeof(header));

    word* layer_background = new word[header.layer_size_x * header.layer_size_y];
    word* layer_foreground = new word[header.layer_size_x * header.layer_size_y];
    file->Read(layer_background, header.layer_size_x * header.layer_size_y * sizeof(word));
    file->Read(layer_foreground, header.layer_size_x * header.layer_size_y * sizeof(word));

    sTileset tileset;
    if (strcmp_ci(tilesetFilename + strlen(tilesetFilename) - 4, ".vsp") == 0)
      success = tileset.Import_VSP(tilesetFilename, fs);
    else
      success = tileset.Load(tilesetFilename, fs);

    sLayer layer[2];

    if (success)
    {
      // process map and see if the map has tiles that are out of range
      int highestTileIndex = 0;
      for (int j=0; j<header.layer_size_y; j++)
        for (int i=0; i<header.layer_size_x; i++)
          if (layer_background[j * header.layer_size_x + i] >= highestTileIndex)
            highestTileIndex = layer_background[j * header.layer_size_x + i];
          else if (layer_foreground[j * header.layer_size_x + i] >= highestTileIndex)
            highestTileIndex = layer_foreground[j * header.layer_size_x + i];

      if (highestTileIndex >= tileset.GetNumTiles())
        success = false;

      // transfer data across into the sMap now...
      if (success)
      {
        layer[0].SetName("Background");
        layer[1].SetName("Foreground");
        layer[0].Resize(header.layer_size_x, header.layer_size_y);
        layer[1].Resize(header.layer_size_x, header.layer_size_y);

        for (int j=0; j<header.layer_size_y; j++)
          for (int i=0; i<header.layer_size_x; i++)
          {
            layer[0].SetTile(i,j, layer_background[j * header.layer_size_x + i]);

            if (layer_foreground[j * header.layer_size_x + i])
            layer[1].SetTile(i,j, layer_foreground[j * header.layer_size_x + i]);
            else
              layer[1].SetTile(i,j, tileset.GetNumTiles());
          }

        tileset.AppendTiles(1);
        memset(tileset.GetTile(tileset.GetNumTiles() - 1).GetPixels(), 0, 256 * sizeof(RGBA));
        m_Tileset = tileset;
        AppendLayer(layer[0]);
        AppendLayer(layer[1]);
        SetMusicFile((char*)header.music_fname);
        SetStartX(header.x_start);
        SetStartX(header.y_start);
        SetStartDirection(4);

        // calculate the parallax mode
        for (int i=0; i<2; i++)
        {
          // FIXME (set parallax properly)
//          GetLayer(i).SetParallaxX(1, 1);
//          GetLayer(i).SetParallaxY(1, 1);
//          GetLayer(i).SetScrollingX(1, 1);
//          GetLayer(i).SetScrollingX(1, 1);
        }

        switch(header.parallax_mode)
        {
          case 0:
            SetStartLayer(0);
            break;

          case 1:
            SetStartLayer(1);
            break;

          case 2:
            // FIXME (set parallax properly)
            SetStartLayer(1);
//            GetLayer(0).SetParallaxX(header.parallax_multiplier, header.parallax_divisor);
//            GetLayer(0).SetParallaxY(header.parallax_multiplier, header.parallax_divisor);
            break;

          case 3:
            // FIXME (set parallax properly)
            SetStartLayer(0);
//            GetLayer(1).SetParallaxX(header.parallax_multiplier, header.parallax_divisor);
//            GetLayer(1).SetParallaxY(header.parallax_multiplier, header.parallax_divisor);
            break;
        }
      }
    }

    // cleanup
    delete[] layer_background;
    delete[] layer_foreground;
  }
  else if (strcmp(signature, "MAPĆ¹5") == 0)
  {
    V2MAP_HEADER header;
    V2MAP_LAYERINFO LayerInfo[7];
    sTileset tileset;
    word *mapLayer[7];
    int i,j,k;
    int highestTileIndex = 0;

    file->Read(&header, sizeof(header));
    for (i=0; i<header.num_layers; i++)
    {
      file->Read(LayerInfo + i, sizeof(V2MAP_LAYERINFO));
      //bug for v2's map: two bytes are added for no reason
      word w;
      file->Read(&w, 2);
    }

    // get info about map and uncompress it
    for (i=0; i<header.num_layers; i++)
      mapLayer[i] = new word[LayerInfo[i].size_x * LayerInfo[i].size_y];

    for (i=0; i<header.num_layers; i++)
    {
      // god, this is so dumb. It's supposed to be the buffersize, but do I look like I need it?
      file->Read(&j, 4);
      for (j=0; j<LayerInfo[i].size_x*LayerInfo[i].size_y; j++)
      {
        word value;
        byte run;
        
        file->Read(&value, sizeof(word));

        if ((value & 0xFF00) == 0xFF00)
        {
          run = (byte)value & 0x00FF;
          file->Read(&value, sizeof(word));
          
          mapLayer[i][j] = value;
          for (k=1; k<run; k++)
          {
            j++;
            mapLayer[i][j] = value;
          }
        }
        else
        {
          mapLayer[i][j]  = value;
        }
      }
    }

    if (strcmp_ci(tilesetFilename + strlen(tilesetFilename) - 4, ".vsp") == 0)
      success = tileset.Import_VSP(tilesetFilename);
    else
      success = tileset.Load(tilesetFilename);


    // transfer map array into the class
    if (success)
    {
      highestTileIndex = 0;
      // check for any tile index larger than the tilset's index
      for (i=0; i<header.num_layers; i++)
        for (j=0; j<LayerInfo[i].size_x*LayerInfo[i].size_y; j++)
          if (mapLayer[i][j] >= highestTileIndex)
            highestTileIndex = mapLayer[i][j];

      if (highestTileIndex >= tileset.GetNumTiles())
        success = false;

    if (success)
      {
        sLayer *layer;
        layer = new sLayer[header.num_layers];

        for (i=0; i<header.num_layers; i++)
        {
          char Name[7];
          memcpy(Name, "Layer A", 8);
          Name[6] += i;

          layer[i].SetName(Name);
          layer[i].Resize(LayerInfo[i].size_x, LayerInfo[i].size_y);
        }

        for (i=0; i<header.num_layers; i++)
        {
          for (j=0; j<LayerInfo[i].size_y; j++)
            for (k=0; k<LayerInfo[i].size_x; k++)
              layer[i].SetTile(k, j, mapLayer[i][(j * LayerInfo[i].size_x) + k]);

          // FIXME: set parallax properly
//          layer[i].SetParallaxX(LayerInfo[i].multx, LayerInfo[i].pdivx);
//          layer[i].SetParallaxY(LayerInfo[i].multy, LayerInfo[i].pdivy);
//          layer[i].SetScrollingX(1,1);
//          layer[i].SetScrollingY(1,1);
        }

        for (i=0; i<(int)strlen((char*)header.renderstring); i++)
          switch(header.renderstring[i])
          {
          case '1': AppendLayer(layer[0]); j = 0; break;
          case '2': AppendLayer(layer[1]); j = 1; break;
          case '3': AppendLayer(layer[2]); j = 2; break;
          case '4': AppendLayer(layer[3]); j = 3; break;
          case '5': AppendLayer(layer[4]); j = 4; break;
          case '6': AppendLayer(layer[5]); j = 5; break;
          case 'E': SetStartLayer(j); break;
          }

        SetMusicFile((char*)header.music_name);
        SetStartX(header.x_start);
        SetStartY(header.y_start);
        m_Tileset = tileset;

        delete[] layer;
      } 
    }

    for (i=0; i<header.num_layers; i++)
      delete mapLayer[i];
  }

  file->Close();
  return success;
}