示例#1
0
		void Client::TakeMapShot(){
			
			try{
				std::string name = MapShotPath();
				{
					std::unique_ptr<IStream> stream(FileManager::OpenForWriting(name.c_str()));
					try{
						GameMap *map = GetWorld()->GetMap();
						if(map == nullptr){
							SPRaise("No map loaded");
						}
						map->Save(stream.get());
					}catch(...){
						throw;
					}
				}
				
				std::string msg;
				msg = _Tr("Client", "Map saved: {0}", name);
				ShowAlert(msg, AlertType::Notice);
			}catch(const Exception& ex){
				std::string msg;
				msg = _Tr("Client", "Saving map failed: ");
				msg += ex.GetShortMessage();
				ShowAlert(msg, AlertType::Error);
				SPLog("Saving map failed: %s", ex.what());
			}catch(const std::exception& ex){
				std::string msg;
				msg = _Tr("Client", "Saving map failed: ");
				msg += ex.what();
				ShowAlert(msg, AlertType::Error);
				SPLog("Saving map failed: %s", ex.what());
			}
		}
示例#2
0
		void Runner::RunProtected() {
			SPADES_MARK_FUNCTION();
			std::string err;
			try{
				Run();
			}catch(const spades::Exception& ex){
				err = ex.GetShortMessage();
				SPLog("[!] Unhandled exception in SDLRunner:\n%s", ex.what());
			}catch(const std::exception& ex){
				err = ex.what();
				SPLog("[!] Unhandled exception in SDLRunner:\n%s", ex.what());
			}
			if(!err.empty()){
				
				std::string msg = err;
				msg = _Tr("Main", "A serious error caused OpenSpades to stop working:\n\n{0}\n\nSee SystemMessages.log for more details.", msg);
				
				
				SDL_InitSubSystem(SDL_INIT_VIDEO);
				if(SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, _Tr("Main", "OpenSpades Fatal Error").c_str(), msg.c_str(), nullptr)) {
					// showing dialog failed.
					// TODO: do appropriate action
				}
		
				
			}
		}
		void Client::PlayerCapturedIntel(spades::client::Player *p){
			std::string msg;
			{
				std::string holderName = chatWindow->TeamColorMessage(p->GetName(), p->GetTeamId());
				
				std::string otherTeamName = chatWindow->TeamColorMessage(world->GetTeam(1 - p->GetTeamId()).name,
																		 1 - p->GetTeamId());
				msg = _Tr("Client", "{0} captured {1}'s intel", holderName, otherTeamName);
				chatWindow->AddMessage(msg);
			}
			
			if ((int)cg_centerMessage != 0){
				std::string holderName = p->GetName();
				std::string otherTeamName = world->GetTeam(1 - p->GetTeamId()).name;
				msg = _Tr("Client", "{0} captured {1}'s Intel.", holderName, otherTeamName);
				NetLog("%s", msg.c_str());
				centerMessageView->AddMessage(msg);
			}
			
			if(world->GetLocalPlayer() && !IsMuted()){
				if(p->GetTeamId() == world->GetLocalPlayer()->GetTeamId()){
					Handle<IAudioChunk> chunk = audioDevice->RegisterSound("Sounds/Feedback/CTF/YourTeamCaptured.wav");
					audioDevice->PlayLocal(chunk, AudioParam());
				}else{
					Handle<IAudioChunk> chunk = audioDevice->RegisterSound("Sounds/Feedback/CTF/EnemyCaptured.wav");
					audioDevice->PlayLocal(chunk, AudioParam());
				}
			}
		}
示例#4
0
文件: ringbuf.c 项目: semenovf/cwt
/**
 * Write bytes from file into ring buffer
 *
 * @param rb the ring buffer
 * @param fd file descriptor
 * @param n max bytes to write
 * @return bytes written into the ring buffer, or -1 if error
 */
ssize_t rb_write_from_file(CwtRingBuffer* rb, int fd, size_t n)
{
	BYTE ibuf[256];
	size_t total_br = 0;
	CwtUnistdNS *ns = cwt_unistd_ns();

	if( fd < 0 ) {
		print_error(_Tr("invalid file descriptor"));
		return 0;
	}

	while( total_br < n ) {
		/* TODO fix unsigned int cast */
		ssize_t br = ns->read(fd, ibuf, (UINT)(n - total_br));

		if( br == 0 ) /* end of file */
			break;

		if( br < 0 ) {
			printf_error(_Tr("read file error: %s"), strerror(errno));
			return (ssize_t)-1;
		}

		total_br += br;

		if( !rb_push_back(rb, ibuf, br) ) {
			return (ssize_t)-1;
		}
	}

	return (ssize_t)total_br;
}
示例#5
0
String AbnfGenContext::generate () const
{
	String r;

	// Before normalization
	size_t origRulesCount = m_rulelist.elements().size();

	if (! m_rulelist.normalize()) {
		Logger::error(_Tr("Failed to normalize ABNF rulelist"));
		return String();
	}

	String ttcText(generateTransitionTablesClass(m_rulelist, transitionType(), sourceDataType()));
	String ttText(generateTransitionTables(m_rulelist, m_options, origRulesCount));

	if (ttcText.isEmpty() || ttText.isEmpty())
		return String();

	String headerText(generateHeader(sourceDataType()));
	String enumText(generateEnum(m_rulelist, origRulesCount));
	String actionFlags(generateActionArgs(m_rulelist, origRulesCount));
	String actionsText(generateActions(m_rulelist, origRulesCount, sourceDataType()));

	r << headerText   << String::EndOfLine
	  << enumText     << String::EndOfLine
	  << ttcText      << String::EndOfLine
	  << actionFlags  << String::EndOfLine
	  << ttText       << String::EndOfLine
	  << actionsText;

	return r;
}
示例#6
0
		void Client::LocalPlayerBuildError(BuildFailureReason reason) {
			SPADES_MARK_FUNCTION();

			if (!cg_alerts) {
				PlayAlertSound();
				return;
			}

			switch (reason) {
				case BuildFailureReason::InsufficientBlocks:
					ShowAlert(_Tr("Client", "Insufficient blocks."), AlertType::Error);
					break;
				case BuildFailureReason::InvalidPosition:
					ShowAlert(_Tr("Client", "You cannot place a block there."), AlertType::Error);
					break;
			}
		}
		void Client::PlayerDropIntel(spades::client::Player *p) {
			std::string msg;
			{
				std::string holderName = chatWindow->TeamColorMessage(p->GetName(), p->GetTeamId());
				std::string otherTeamName = chatWindow->TeamColorMessage(world->GetTeam(1 - p->GetTeamId()).name,
																		 1 - p->GetTeamId());
				msg = _Tr("Client", "{0} dropped {1}'s intel", holderName, otherTeamName);
				chatWindow->AddMessage(msg);
			}
			
			if ((int)cg_centerMessage != 0){
				std::string holderName = p->GetName();
				std::string otherTeamName = world->GetTeam(1 - p->GetTeamId()).name;
				msg = _Tr("Client", "{0} dropped {1}'s Intel", holderName, otherTeamName);
				NetLog("%s", msg.c_str());
				centerMessageView->AddMessage(msg);
			}
		}
示例#8
0
void SepaloidBootstrap::connectAll()
{
	plan_map_t::iterator it = m_planMap.begin();
	plan_map_t::iterator itEnd = m_planMap.end();

	for(; it != itEnd; it++ ) {
		JQ_DEBUGF(_Tr("Connecting signal: %s"), it->first.c_str());
		it->second->connectAll();
	}
}
LoginDialog::LoginDialog(validator_f validator, bool loopMode, QWidget* parent)
	: QDialog(parent)
	, m_validator(validator)
    , m_loopMode(loopMode)
	, m_loginOk(false)
{
	this->setModal(true);
	this->setWindowTitle(QSTRING_FROM_CHARARRAY(_Tr("Login")));

	m_pass = new PasswordInput(this);
    m_pass->setMinimumWidth(200);

    m_buttonBox = new QDialogButtonBox(this);
    m_buttonBox->setOrientation(Qt::Horizontal);
    m_buttonBox->setStandardButtons(/*QDialogButtonBox::Cancel|*/QDialogButtonBox::Ok);

    m_warnImg = new QLabel(this);
    m_warnImg->setPixmap(QPixmap(":/images/exclam.png"));
    m_warnText = new QPlainTextEdit(this);
    m_warnText->setMaximumHeight(100);
    m_warnText->setFrameStyle(QFrame::NoFrame);
    m_warnText->setReadOnly(true);

    // I could not get results by changing the background color in this way (Qt v4.7)
    //
    //m_warnText->setBackgroundRole(QPalette::Window);
    //
    // and this
    //
    //QPalette pal = m_warnText->palette();
    //pal.setColor(m_warnText->foregroundRole(), Qt::blue);
    //m_warnText->setPalette(pal);
    //
    // but works only this way
    QColor bg = this->palette().window().color();
    m_warnText->setStyleSheet(QString("background-color: %1;").arg(bg.name()));

    m_warnText->hide();
    m_warnImg->hide();

	QFormLayout *formLayout = new QFormLayout;
	formLayout->addRow("You are:", new QLabel("anonymous", this));
	formLayout->addRow("Password:", m_pass);
	formLayout->addRow(m_warnImg, m_warnText);
	formLayout->addRow(m_buttonBox);

	formLayout->setSizeConstraint(QLayout::SetFixedSize);
    this->setLayout(formLayout);

	connect(m_buttonBox, SIGNAL(accepted()), this, SLOT(accept()));
	connect(m_pass, SIGNAL(gotFocus()), this, SLOT(clearLoginFailedWarning()));

	this->resize(sizeHint());
}
		void Client::PlayerLeaving(spades::client::Player *p) {
			{
				std::string msg;
				msg = _Tr("Client", "Player {0} has left", chatWindow->TeamColorMessage(p->GetName(), p->GetTeamId()));
				chatWindow->AddMessage(msg);
			}
			{
				std::string msg;
				msg = _Tr("Client", "Player {0} has left", p->GetName());
				
				auto col = p->GetTeamId() < 2 ?
				world->GetTeam(p->GetTeamId()).color :
				IntVector3::Make(255, 255, 255);
				
				NetLog("%s", msg.c_str());
				scriptedUI->RecordChatLog(msg,
										  MakeVector4(col.x / 255.f, col.y / 255.f,
													  col.z / 255.f, 0.8f));
			}
		}
示例#11
0
文件: dl.cpp 项目: semenovf/jq
void DlFactory::closeDl(const char_type *name)
{
	JQ_ASSERT(name);
	const DlCache::iterator it(m_dlCache.find(name));

	if( it != m_dlCache.end() ) {
		delete it->second;
		m_dlCache.erase(it);
	} else {
		JQ_WARNF(_Tr("Wrong dynamic library: '%s'"), name);
	}
}
示例#12
0
文件: dl.cpp 项目: semenovf/jq
DlClassFactory* DlFactory::getClassFactoryInstance( Dl *dl )
{
	if( !dl ) {
		if( !this->getLastError() ) {
			JQ_ERROR(_Tr("dynamic library descriptor is null: unexpected cause"));
			this->setError(_Tr("dynamic library descriptor is null: unexpected cause"));
		}
		return NULL;
	}

	if( !dl->isOpened() ) {
		JQ_ERROR(_Tr("dynamic library does not opened"));
		this->setError(_Tr("dynamic library does not opened"));
		return NULL;
	}


	DlClassFactory* (*classFactoryInstance)();
	*(void**)(&classFactoryInstance) = dl->symbol("getClassFactoryInstance");

	if( !classFactoryInstance ) {
		JQ_ERROR(_Tr("symbol 'getClassFactoryInstance' not found in dynamic library"));
		this->setError(_Tr("symbol 'getClassFactoryInstance' not found in dynamic library"));
		return NULL;
	}

	DlClassFactory *cf = (*classFactoryInstance)();
	return cf;
}
		void Client::TeamCapturedTerritory(int teamId,
										   int terId) {
			TCGameMode::Territory *ter = static_cast<TCGameMode *>(world->GetMode())->GetTerritory(terId);
			int old = ter->ownerTeamId;
			std::string msg;
			std::string teamName = chatWindow->TeamColorMessage(world->GetTeam(teamId).name,
																teamId);
			if(old < 2){
				std::string otherTeam = chatWindow->TeamColorMessage(world->GetTeam(old).name,
																	 old);
				msg = _Tr("Client", "{0} captured {1}'s territory", teamName, otherTeam);
			}else{
				msg = _Tr("Client", "{0} captured an neutral territory", teamName);
			}
			chatWindow->AddMessage(msg);
			
			if ((int)cg_centerMessage != 0){
				teamName = world->GetTeam(teamId).name;
				if (old < 2){
					std::string otherTeam = world->GetTeam(old).name;
					msg = _Tr("Client", "{0} captured {1}'s Territory", teamName, otherTeam);
				}
				else{
					msg = _Tr("Client", "{0} captured an Neutral Territory", teamName);
				}
				NetLog("%s", msg.c_str());
				centerMessageView->AddMessage(msg);
			}

			if(world->GetLocalPlayer() && !IsMuted()){
				if(teamId == world->GetLocalPlayer()->GetTeamId()){
					Handle<IAudioChunk> chunk = audioDevice->RegisterSound("Sounds/Feedback/TC/YourTeamCaptured.wav");
					audioDevice->PlayLocal(chunk, AudioParam());
				}else{
					Handle<IAudioChunk> chunk = audioDevice->RegisterSound("Sounds/Feedback/TC/EnemyCaptured.wav");
					audioDevice->PlayLocal(chunk, AudioParam());
				}
			}
			
		}
示例#14
0
文件: dl.cpp 项目: semenovf/jq
DlSymbol Dl::symbol( const char* sym_name )
{
	JQ_ASSERT(sym_name);
	// Library is not opened
	if( !isOpened() ) { return NULL; }
#ifdef _WIN32
	DlSymbol sym = GetProcAddress(m_handle, sym_name);
	if( !sym ) {
		// TODO setError
		JQ_ERRORF(_Tr("%s: symbol not found"), sym_name);

		LPVOID lpMsgBuf;
		FormatMessage(
		    FORMAT_MESSAGE_ALLOCATE_BUFFER |
		    FORMAT_MESSAGE_FROM_SYSTEM |
		    FORMAT_MESSAGE_IGNORE_INSERTS,
		    NULL,
		    GetLastError(),
		    MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
		    (LPTSTR) &lpMsgBuf,
		    0,
		    NULL
		);
		JQ_ERROR(lpMsgBuf);
		// Free the buffer.
		LocalFree( lpMsgBuf );
	}
#else
	::dlerror(); // clear error
	DlSymbol sym = ::dlsym( m_handle, sym_name );
	if( !sym ) {
		// TODO setError
		JQ_ERRORF(_Tr("%s: symbol not found"), sym_name);
		JQ_ERROR( ::dlerror() );
	}
#endif
	return sym;
}
		void Client::TeamWon(int teamId){
			std::string msg;
			msg = chatWindow->TeamColorMessage(world->GetTeam(teamId).name,
											   teamId);
			msg = _Tr("Client", "{0} wins!", msg);
			chatWindow->AddMessage(msg);
			
			msg = world->GetTeam(teamId).name;
			msg = _Tr("Client", "{0} Wins!", msg);
			NetLog("%s", msg.c_str());
			centerMessageView->AddMessage(msg);
			
			scriptedUI->RecordChatLog(msg, MakeVector4(1.f, 1.f, 1.f, 0.8f));
			
			if(world->GetLocalPlayer()){
				if(teamId == world->GetLocalPlayer()->GetTeamId()){
					Handle<IAudioChunk> chunk = audioDevice->RegisterSound("Sounds/Feedback/Win.wav");
					audioDevice->PlayLocal(chunk, AudioParam());
				}else{
					Handle<IAudioChunk> chunk = audioDevice->RegisterSound("Sounds/Feedback/Lose.wav");
					audioDevice->PlayLocal(chunk, AudioParam());
				}
			}
		}
示例#16
0
void SettingsArchiverBin::restoreNode( AbstractNode * /*node*/, std::istream& is)
{
	if( m_settings->isError() ) return;


	int8_t nodeType;
	_read<int8_t>(is, &nodeType);
/*
	switch( nodeType ) {
	case AbstractNode::Map:
		int32_t sz;
		__read<int32_t>(in, &sz);
		node = new MapNode();
		for( int i = 0; i < sz; i++ ) {
			restore(node, in);
		}

		for( MapNode::const_iterator itm = dynamic_cast<MapNode*>(node)->begin();
				itm != dynamic_cast<MapNode*>(node)->end(); itm++ ) {
			__write_string(out, itm->first.c_str(), itm->first.length());
			save(itm->second, out);
		}

		break;

	case AbstractNode::Vector:
		__write<int32_t>(out, dynamic_cast<VectorNode*>(node)->size());

		for( VectorNode::const_iterator itv = dynamic_cast<VectorNode*>(node)->begin();
				itv != dynamic_cast<VectorNode*>(node)->end(); itv++ ) {
			save(*itv, out);
		}
		break;

	case AbstractNode::Scalar: {
			jq::String s(dynamic_cast<ScalarNode*>(node)->value());
			__write_string(out, s.c_str(), s.length());
		}
		break;

	default:
		JQ_ERROR("invalid node type");
		this->ok(false);
		break;
	}*/

	m_settings->setError(_Tr("invalid node type"));
}
示例#17
0
		void Client::PlayerSentChatMessage(spades::client::Player *p,
										   bool global,
										   const std::string &msg){
			{
				std::string s;
				if(global)
					/// prefix added to global chat messages.
					s = _Tr("Client", "[Global] ");
				s += ChatWindow::TeamColorMessage(p->GetName(), p->GetTeamId());
				s += ": ";
				s += msg;
				chatWindow->AddMessage(s);
			}
			{
				std::string s;
				if(global)
					s = "[Global] ";
				s += p->GetName();
				s += ": ";
				s += msg;
				
				auto col = p->GetTeamId() < 2 ?
				world->GetTeam(p->GetTeamId()).color :
				IntVector3::Make(255, 255, 255);
				
				scriptedUI->RecordChatLog(s,
										  MakeVector4(col.x / 255.f, col.y / 255.f,
													  col.z / 255.f, 0.8f));
				
			}
			if(global)
				NetLog("[Global] %s (%s): %s",
					   p->GetName().c_str(),
					   world->GetTeam(p->GetTeamId()).name.c_str(),
					   msg.c_str());
			else
				NetLog("[Team] %s (%s): %s",
					   p->GetName().c_str(),
					   world->GetTeam(p->GetTeamId()).name.c_str(),
					   msg.c_str());
			
			
			if((!IsMuted()) && (int)cg_chatBeep) {
				Handle<IAudioChunk> chunk = audioDevice->RegisterSound("Sounds/Feedback/Chat.wav");
				audioDevice->PlayLocal(chunk, AudioParam());
			}
		}
示例#18
0
文件: dl.cpp 项目: semenovf/jq
void DlFactory::closeDl(Dl *dl)
{
	const DlCache::iterator it_end = m_dlCache.end();
	DlCache::iterator it = m_dlCache.begin();

	for( ; it != it_end; it++) {

		if( it->second == dl ) {
			delete it->second;
			m_dlCache.erase(it);
			break;
		}
	}

	if( it == it_end ) {
		JQ_WARNF(_Tr("Wrong dynamic library: %p"), dl);
	}
}
示例#19
0
		void MainScreen::DrawStartupScreen() {
			SPADES_MARK_FUNCTION();
			Handle<client::IImage> img;
			Vector2 scrSize = {renderer->ScreenWidth(),
				renderer->ScreenHeight()};
			
			renderer->SetColorAlphaPremultiplied(MakeVector4(0, 0, 0, 1.));
			img = renderer->RegisterImage("Gfx/White.tga");
			renderer->DrawImage(img, AABB2(0, 0,
										   scrSize.x, scrSize.y));
			
			std::string str = _Tr("MainScreen", "NOW LOADING");
			Vector2 size = font->Measure(str);
			Vector2 pos = MakeVector2(scrSize.x - 16.f, scrSize.y - 16.f);
			pos -= size;
			font->DrawShadow(str, pos, 1.f, MakeVector4(1,1,1,1), MakeVector4(0,0,0,0.5));
			
			renderer->FrameDone();
			renderer->Flip();
		}
示例#20
0
DlHandle dl_open(const CWT_CHAR *path, BOOL global, BOOL resolve)
{
	DlHandle h = NULL;
	char *path_utf8;

	dlerror(); /* clear error */

	path_utf8 = cwt_textcodec_ns()->toUtf8(path);
	h = dlopen( path, (global ? RTLD_GLOBAL : RTLD_LOCAL) | ( resolve ? RTLD_NOW : RTLD_LAZY ) );
	CWT_FREE(path_utf8);

	if( !h ) {
		CWT_CHAR *dlerror_str;

		dlerror_str = cwt_textcodec_ns()->fromUtf8(dlerror());
		cwt_logger_ns()->error( _Tr("%s: failed to open dynamic library: %s"), path, dlerror_str );
		CWT_FREE(dlerror_str);
	}

	return h;
}
示例#21
0
文件: socket_p.c 项目: semenovf/cwt
BOOL __socket_initSockAddrIn(struct sockaddr_in *saddr, const CWT_CHAR *inetAddr, UINT16 port)
{
	BOOL ok = TRUE;

	cwt_bzero(saddr, sizeof(*saddr));
	saddr->sin_family      = AF_INET;
	saddr->sin_port        = htons(port);

	if (!inetAddr) {
		saddr->sin_addr.s_addr = htonl(INADDR_ANY);
	} else {
		char *inetAddrLatin1;
		inetAddrLatin1 = cwt_textcodec_ns()->toLatin1(inetAddr);

		if( !inet_aton(inetAddrLatin1, &saddr->sin_addr) ) {
			do {
				struct hostent *phost;

				phost = gethostbyname(inetAddrLatin1);

				if (phost == (struct hostent *)NULL) {
					cwt_logger_ns()->error(_Tr("%s: host not found"), inetAddr);
					/*printf("h_errno = %d\n", h_errno);*/
					ok = FALSE;
					break;
				}

				memcpy(&saddr->sin_addr, phost->h_addr, sizeof(saddr->sin_addr));

			} while(FALSE);
		}
		CWT_FREE(inetAddrLatin1);
	}

	return ok;
}
示例#22
0
文件: socket_p.c 项目: semenovf/cwt
CwtSocket* __socket_openTypified(CwtSocketType socketType, BOOL is_nonblocking)
{
	SOCKET sockfd;
	CwtSocket *sd;

	int nativeType;
	int domain = AF_INET;

	if( !__socket_allowSockets() ) {
		cwt_logger_ns()->error(_Tr("network sockets not allowed in this system"));
		return NULL;
	}

	domain = socketType != Cwt_LocalSocket
			? AF_INET
			: AF_UNIX;

	nativeType = (socketType == Cwt_TcpSocket || socketType == Cwt_LocalSocket)
			? SOCK_STREAM
			: SOCK_DGRAM;

	sockfd = socket(domain, nativeType, 0);
    if( sockfd < 0 ) {
    	cwt_logger_ns()->error(_Tr("failed to open socket")
    			_CWT_SOCKET_LOG_FMTSUFFIX
    			, _CWT_SOCKET_LOG_ARGS);
		return NULL;
    }

	if( is_nonblocking ) {
		if (!__socket_setNonBlockingNative(sockfd, is_nonblocking)) {
			cwt_logger_ns()->error(_Tr("set/unset socket non-blocking mode failed"));
			__socket_closeNative(sockfd);
			return NULL;
		}
	}

	switch(socketType) {
	case Cwt_LocalSocket:
		sd = (CwtSocket*)CWT_MALLOCT(CwtLocalSocket);
		cwt_bzero(sd, sizeof(CwtLocalSocket));
		break;
	case Cwt_McastSocket:
		sd = (CwtSocket*)CWT_MALLOCT(CwtMcastSocket);
		cwt_bzero(sd, sizeof(CwtMcastSocket));
		break;
	case Cwt_UdpSocket:
		sd = (CwtSocket*)CWT_MALLOCT(CwtUdpSocket);
		cwt_bzero(sd, sizeof(CwtUdpSocket));
		break;
	case Cwt_TcpSocket:
	default:
		sd = (CwtSocket*)CWT_MALLOCT(CwtTcpSocket);
		cwt_bzero(sd, sizeof(CwtTcpSocket));
		break;
	}

	sd->sockfd      = sockfd;
	sd->type        = socketType;
	sd->is_listener = FALSE;


	__socket_nsockets_opened++;

	return (CwtSocket*)sd;
}
示例#23
0
int main(int argc, char ** argv)
{
#ifdef WIN32
	SetUnhandledExceptionFilter( UnhandledExceptionProc );
#endif

	for(int i = 1; i < argc;) {
			int ret = argsHandler(argc, argv, i);
			if(!ret) {
				// ignore unknown arg
				i++;
			}
		}

		if ( cg_printVersion ) {
			printf( "%s\n", PACKAGE_STRING );
			return 0;
		}

		if ( cg_printHelp ) {
			printHelp( argv[0] );
			return 0;
		}


	std::unique_ptr<SplashWindow> splashWindow;

	try{

		// start recording backtrace
		spades::reflection::Backtrace::StartBacktrace();
		SPADES_MARK_FUNCTION();

		// show splash window
		// NOTE: splash window uses image loader, which assumes backtrace is already initialized.
		splashWindow.reset(new SplashWindow());
		auto showSplashWindowTime = SDL_GetTicks();
		auto pumpEvents = [&splashWindow] { splashWindow->PumpEvents(); };

		// initialize threads
		spades::Thread::InitThreadSystem();
		spades::DispatchQueue::GetThreadQueue()->MarkSDLVideoThread();

		SPLog("Package: " PACKAGE_STRING);
		// setup user-specific default resource directories
#ifdef WIN32
		static wchar_t buf[4096];
		GetModuleFileNameW(NULL, buf, 4096);
		std::wstring appdir = buf;
		appdir = appdir.substr(0, appdir.find_last_of(L'\\')+1);

		if(SUCCEEDED(SHGetFolderPathW(NULL, CSIDL_APPDATA, NULL, 0, buf))){
			std::wstring datadir = buf;
			datadir += L"\\OpenSpades\\Resources";
			spades::FileManager::AddFileSystem(new spades::DirectoryFileSystem(Utf8FromWString(datadir.c_str()), true));
		}
		
		spades::FileManager::AddFileSystem(new spades::DirectoryFileSystem(Utf8FromWString((appdir + L"Resources").c_str()), false));
		
		//fltk has a console window on windows (can disable while building, maybe use a builtin console for a later release?)
		HWND hCon = GetConsoleWindow();
		if( NULL != hCon ) {
			setIcon( hCon );
		}

#elif defined(__APPLE__)
		std::string home = getenv("HOME");
		spades::FileManager::AddFileSystem
		(new spades::DirectoryFileSystem("./Resources", false));

		// OS X application is made of Bundle, which contains its own Resources directory.
		{
			char *baseDir = SDL_GetBasePath();
			if(baseDir) {
				spades::FileManager::AddFileSystem
				(new spades::DirectoryFileSystem(baseDir, false));
				SDL_free(baseDir);
			}
		}

		spades::FileManager::AddFileSystem
		(new spades::DirectoryFileSystem(home+"/Library/Application Support/OpenSpades/Resources", true));
#else
		std::string home = getenv("HOME");

		spades::FileManager::AddFileSystem
		(new spades::DirectoryFileSystem("./Resources", false));

		spades::FileManager::AddFileSystem(new spades::DirectoryFileSystem(CMAKE_INSTALL_PREFIX "/" OPENSPADES_INSTALL_RESOURCES, false));

		std::string xdg_data_home = home+"/.local/share";

		if (getenv("XDG_DATA_HOME") == NULL) {
			SPLog("XDG_DATA_HOME not defined. Assuming that XDG_DATA_HOME is ~/.local/share");
		}
		else {
			std::string xdg_data_home = getenv("XDG_DATA_HOME");
			SPLog("XDG_DATA_HOME is %s", xdg_data_home.c_str());
		}

		struct stat info;

		if ( stat((xdg_data_home+"/openspades").c_str(), &info ) != 0 ) {
			if ( stat((home+"/.openspades").c_str(), &info ) != 0) { }
			else if( info.st_mode & S_IFDIR ) {
				SPLog("Openspades directory in XDG_DATA_HOME not found, though old directory exists. Trying to resolve compatibility problem.");

				if (rename( (home+"/.openspades").c_str() , (xdg_data_home+"/openspades").c_str() ) != 0) {
					SPLog("Failed to move old directory to new.");
				} else {
					SPLog("Successfully moved old directory.");

					if (mkdir((home+"/.openspades").c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) == 0) {
						SDL_RWops *io = SDL_RWFromFile((home+"/.openspades/CONTENT_MOVED_TO_NEW_DIR").c_str(), "wb");
						if (io != NULL) {
							const char* text = ("Content of this directory moved to "+xdg_data_home+"/openspades").c_str();
							io->write(io, text, strlen(text), 1);
							io->close(io);
						}
					}
				}
			}
		}

		spades::FileManager::AddFileSystem
		(new spades::DirectoryFileSystem(xdg_data_home+"/openspades/Resources", true));

#endif

		// start log output to SystemMessages.log
		try{
			spades::StartLog();
		}catch(const std::exception& ex){
			SDL_InitSubSystem(SDL_INIT_VIDEO);
			auto msg = spades::Format("Failed to start recording log because of the following error:\n{0}\n\n"
									  "OpenSpades will continue to run, but any critical events are not logged.", ex.what());
			if(SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_WARNING,
										"OpenSpades Log System Failure",
										msg.c_str(), splashWindow->GetWindow())) {
				// showing dialog failed.
			}
		}
		SPLog("Log Started.");

		// load preferences.
		spades::Settings::GetInstance()->Load();
		pumpEvents();

		// dump CPU info (for debugging?)
		{
			spades::CpuID cpuid;
			SPLog("---- CPU Information ----");
			SPLog("Vendor ID: %s", cpuid.GetVendorId().c_str());
			SPLog("Brand ID: %s", cpuid.GetBrand().c_str());
			SPLog("Supports MMX: %s", cpuid.Supports(spades::CpuFeature::MMX)?"YES":"NO");
			SPLog("Supports SSE: %s", cpuid.Supports(spades::CpuFeature::SSE)?"YES":"NO");
			SPLog("Supports SSE2: %s", cpuid.Supports(spades::CpuFeature::SSE2)?"YES":"NO");
			SPLog("Supports SSE3: %s", cpuid.Supports(spades::CpuFeature::SSE3)?"YES":"NO");
			SPLog("Supports SSSE3: %s", cpuid.Supports(spades::CpuFeature::SSSE3)?"YES":"NO");
			SPLog("Supports FMA: %s", cpuid.Supports(spades::CpuFeature::FMA)?"YES":"NO");
			SPLog("Supports AVX: %s", cpuid.Supports(spades::CpuFeature::AVX)?"YES":"NO");
			SPLog("Supports AVX2: %s", cpuid.Supports(spades::CpuFeature::AVX2)?"YES":"NO");
			SPLog("Supports AVX512F: %s", cpuid.Supports(spades::CpuFeature::AVX512F)?"YES":"NO");
			SPLog("Supports AVX512CD: %s", cpuid.Supports(spades::CpuFeature::AVX512CD)?"YES":"NO");
			SPLog("Supports AVX512ER: %s", cpuid.Supports(spades::CpuFeature::AVX512ER)?"YES":"NO");
			SPLog("Supports AVX512PF: %s", cpuid.Supports(spades::CpuFeature::AVX512PF)?"YES":"NO");
			SPLog("Simultaneous Multithreading: %s", cpuid.Supports(spades::CpuFeature::SimultaneousMT)?"YES":"NO");
			SPLog("Misc:");
			SPLog("%s", cpuid.GetMiscInfo().c_str());
			SPLog("-------------------------");
		}

		// register resource directory specified by Makefile (or something)
#if defined(RESDIR_DEFINED)
		spades::FileManager::AddFileSystem(new spades::DirectoryFileSystem(RESDIR, false));
#endif

		// search current file system for .pak files
		{
			std::vector<spades::IFileSystem*> fss;
			std::vector<spades::IFileSystem*> fssImportant;

			std::vector<std::string> files = spades::FileManager::EnumFiles("");

			struct Comparator {
				static int GetPakId(const std::string& str) {
					if(str.size() >= 4 && str[0] == 'p' &&
					   str[1] == 'a' && str[2] == 'k' &&
					   (str[3] >= '0' && str[3] <= '9')){
						return atoi(str.c_str() + 3);
					}else{
						return 32767;
					}
				}
				static bool Compare(const std::string& a,
									const std::string& b) {
					int pa = GetPakId(a);
					int pb = GetPakId(b);
					if(pa == pb){
						return a < b;
					}else{
						return pa < pb;
					}
				}
			};

			std::sort(files.begin(), files.end(), Comparator::Compare);

			for(size_t i = 0; i < files.size(); i++){
				std::string name = files[i];

				// check extension
				if(name.size() < 4 ||
				   name.rfind(".pak") != name.size() - 4){
					continue;
				}

				if(spades::FileManager::FileExists(name.c_str())) {
					spades::IStream *stream = spades::FileManager::OpenForReading(name.c_str());
					spades::ZipFileSystem *fs = new spades::ZipFileSystem(stream);
					if(name[0] == '_' && false) { // last resort for #198
						SPLog("Pak Registered: %s (marked as 'important')\n", name.c_str());
						fssImportant.push_back(fs);
					}else{
						SPLog("Pak Registered: %s\n", name.c_str());
						fss.push_back(fs);
					}
				}
			}
			for(size_t i = fss.size(); i > 0; i--){
				spades::FileManager::AppendFileSystem(fss[i - 1]);
			}
			for(size_t i = 0; i < fssImportant.size(); i++){
				spades::FileManager::PrependFileSystem(fssImportant[i]);
			}
		}
		pumpEvents();

		// initialize localization system
		SPLog("Initializing localization system");
		spades::LoadCurrentLocale();
		_Tr("Main", "Localization System Loaded");
		pumpEvents();

		// parse args

		// initialize AngelScript
		SPLog("Initializing script engine");
		spades::ScriptManager::GetInstance();
		pumpEvents();

		ThreadQuantumSetter quantumSetter;
		(void)quantumSetter; // suppress "unused variable" warning

		SDL_InitSubSystem(SDL_INIT_VIDEO);

		// we want to show splash window at least for some time...
		pumpEvents();
		auto ticks = SDL_GetTicks();
		if(ticks < showSplashWindowTime + 1500) {
			SDL_Delay(showSplashWindowTime + 1500 - ticks);
		}
		pumpEvents();

		// everything is now ready!
		if( !cg_autoConnect ) {
			if(!((int)cl_showStartupWindow != 0 ||
				 splashWindow->IsStartupScreenRequested())) {
				splashWindow.reset();

				SPLog("Starting main screen");
				spades::StartMainScreen();
			}else{
				splashWindow.reset();

				SPLog("Starting startup window");
				::spades::gui::StartupScreen::Run();
			}
		} else {
			splashWindow.reset();

			spades::ServerAddress host(cg_lastQuickConnectHost.CString(), (int)cg_protocolVersion == 3 ? spades::ProtocolVersion::v075 : spades::ProtocolVersion::v076 );
			spades::StartClient(host, cg_playerName);
		}

		spades::Settings::GetInstance()->Flush();

	}catch(const ExitRequestException&){
		// user changed his mind.
	}catch(const std::exception& ex) {

		try {
			splashWindow.reset(nullptr);
		}catch(...){
		}

		std::string msg = ex.what();
		msg = _Tr("Main", "A serious error caused OpenSpades to stop working:\n\n{0}\n\nSee SystemMessages.log for more details.", msg);

		SPLog("[!] Terminating due to the fatal error: %s", ex.what());

		SDL_InitSubSystem(SDL_INIT_VIDEO);
		if(SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, _Tr("Main", "OpenSpades Fatal Error").c_str(), msg.c_str(), nullptr)) {
			// showing dialog failed.
			// TODO: do appropriate action
		}

	}

    return 0;
}
示例#24
0
		/** Handles movement of joined local player. */
		void Client::UpdateLocalPlayer(float dt) {
			SPADES_MARK_FUNCTION();
			
			auto *player = world->GetLocalPlayer();
			
			PlayerInput inp = playerInput;
			WeaponInput winp = weapInput;
			
			// weapon/tools are disabled while/soon after sprinting
			if(GetSprintState() > 0.001f) {
				winp.primary = false;
				winp.secondary = false;
			}
			
			// don't allow to stand up when ceilings are too low
			if(inp.crouch == false){
				if(player->GetInput().crouch){
					if(!player->TryUncrouch(false)){
						inp.crouch = true;
					}
				}
			}
			
			// don't allow jumping in the air
			if(inp.jump){
				if(!player->IsOnGroundOrWade())
					inp.jump = false;
			}
			
			// weapon/tools are disabled while changing tools
			if(clientPlayers[world->GetLocalPlayerIndex()]->IsChangingTool()) {
				winp.primary = false;
				winp.secondary = false;
			}
			
			// disable weapon while reloading (except shotgun)
			if(player->GetTool() == Player::ToolWeapon &&
			   player->IsAwaitingReloadCompletion() &&
			   !player->GetWeapon()->IsReloadSlow()) {
				winp.primary = false;
			}
			
			player->SetInput(inp);
			player->SetWeaponInput(winp);
			
			//send player input
			// FIXME: send only there are any changed?
			net->SendPlayerInput(inp);
			net->SendWeaponInput(winp);
			
			if(hasDelayedReload) {
				world->GetLocalPlayer()->Reload();
				net->SendReload();
				hasDelayedReload = false;
			}
			
			//PlayerInput actualInput = player->GetInput();
			WeaponInput actualWeapInput = player->GetWeaponInput();
			
			if(actualWeapInput.secondary &&
			   player->IsToolWeapon() &&
			   player->IsAlive()){
			}else{
				if(player->IsToolWeapon()){
					// there is a possibility that player has respawned or something.
					// stop aiming down
					weapInput.secondary = false;
				}
			}
			
			// is the selected tool no longer usable (ex. out of ammo)?
			if(!player->IsToolSelectable(player->GetTool())) {
				// release mouse button before auto-switching tools
				winp.primary = false;
				winp.secondary = false;
				weapInput = winp;
				net->SendWeaponInput(weapInput);
				actualWeapInput = winp = player->GetWeaponInput();
				
				// select another tool
				Player::ToolType t = player->GetTool();
				do{
					switch(t){
						case Player::ToolSpade:
							t = Player::ToolGrenade;
							break;
						case Player::ToolBlock:
							t = Player::ToolSpade;
							break;
						case Player::ToolWeapon:
							t = Player::ToolBlock;
							break;
						case Player::ToolGrenade:
							t = Player::ToolWeapon;
							break;
					}
				}while(!world->GetLocalPlayer()->IsToolSelectable(t));
				SetSelectedTool(t);
			}
			
			// send orientation
			Vector3 curFront = player->GetFront();
			if(curFront.x != lastFront.x ||
			   curFront.y != lastFront.y ||
			   curFront.z != lastFront.z) {
				lastFront = curFront;
				net->SendOrientation(curFront);
			}
			
			lastKills = world->GetPlayerPersistent(player->GetId()).kills;
			
			// show block count when building block lines.
			if(player->IsAlive() &&
			   player->GetTool() == Player::ToolBlock &&
			   player->GetWeaponInput().secondary &&
			   player->IsBlockCursorDragging()) {
				if(player->IsBlockCursorActive()) {
					auto blocks = std::move
					(world->CubeLine(player->GetBlockCursorDragPos(),
									 player->GetBlockCursorPos(),
									 256));
					auto msg = _TrN("Client",
									"{0} block", "{0} blocks",
									blocks.size());
					AlertType type =
					static_cast<int>(blocks.size()) > player->GetNumBlocks() ?
					AlertType::Warning : AlertType::Notice;
					ShowAlert(msg, type, 0.f, true);
				}else{
					// invalid
					auto msg = _Tr("Client", "-- blocks");
					AlertType type = AlertType::Warning;
					ShowAlert(msg, type, 0.f, true);
				}
			}
			
			if(player->IsAlive())
				lastAliveTime = time;
			
			if(player->GetHealth() < lastHealth){
				// ouch!
				lastHealth = player->GetHealth();
				lastHurtTime = world->GetTime();
				
				Handle<IAudioChunk> c;
				switch((rand() >> 3) & 3){
					case 0:
						c = audioDevice->RegisterSound("Sounds/Weapons/Impacts/FleshLocal1.wav");
						break;
					case 1:
						c = audioDevice->RegisterSound("Sounds/Weapons/Impacts/FleshLocal2.wav");
						break;
					case 2:
						c = audioDevice->RegisterSound("Sounds/Weapons/Impacts/FleshLocal3.wav");
						break;
					case 3:
						c = audioDevice->RegisterSound("Sounds/Weapons/Impacts/FleshLocal4.wav");
						break;
				}
				audioDevice->PlayLocal(c, AudioParam());
				
				float hpper = player->GetHealth() / 100.f;
				int cnt = 18 - (int)(player->GetHealth() / 100.f * 8.f);
				hurtSprites.resize(std::max(cnt, 6));
				for(size_t i = 0; i < hurtSprites.size(); i++) {
					HurtSprite& spr = hurtSprites[i];
					spr.angle = GetRandom() * (2.f * static_cast<float>(M_PI));
					spr.scale = .2f + GetRandom() * GetRandom() * .7f;
					spr.horzShift = GetRandom();
					spr.strength = .3f + GetRandom() * .7f;
					if(hpper > .5f) {
						spr.strength *= 1.5f - hpper;
					}
				}
				
			}else{
示例#25
0
		void Client::PlayerKilledPlayer(spades::client::Player *killer,
		                                spades::client::Player *victim, KillType kt) {
			// play hit sound
			if (kt == KillTypeWeapon || kt == KillTypeHeadshot) {
				// don't play on local: see BullethitPlayer
				if (victim != world->GetLocalPlayer()) {
					if (!IsMuted()) {
						Handle<IAudioChunk> c;
						switch (SampleRandomInt(0, 2)) {
							case 0:
								c = audioDevice->RegisterSound("Sounds/Weapons/Impacts/Flesh1.opus");
								break;
							case 1:
								c = audioDevice->RegisterSound("Sounds/Weapons/Impacts/Flesh2.opus");
								break;
							case 2:
								c = audioDevice->RegisterSound("Sounds/Weapons/Impacts/Flesh3.opus");
								break;
						}
						AudioParam param;
						param.volume = 4.f;
						audioDevice->Play(c, victim->GetEye(), param);
					}
				}
			}

			// The local player is dead; initialize the look-you-are-dead cam
			if (victim == world->GetLocalPlayer()) {
				followCameraState.enabled = false;

				Vector3 v = -victim->GetFront();
				followAndFreeCameraState.yaw = atan2(v.y, v.x);
				followAndFreeCameraState.pitch = 30.f * M_PI / 180.f;
			}

			// emit blood (also for local player)
			// FIXME: emiting blood for either
			// client-side or server-side hit?
			switch (kt) {
				case KillTypeGrenade:
				case KillTypeHeadshot:
				case KillTypeMelee:
				case KillTypeWeapon: Bleed(victim->GetEye()); break;
				default: break;
			}

			// create ragdoll corpse
			if (cg_ragdoll && victim->GetTeamId() < 2) {
				Corpse *corp;
				corp = new Corpse(renderer, map, victim);
				if (victim == world->GetLocalPlayer())
					lastMyCorpse = corp;
				if (killer != victim && kt != KillTypeGrenade) {
					Vector3 dir = victim->GetPosition() - killer->GetPosition();
					dir = dir.Normalize();
					if (kt == KillTypeMelee) {
						dir *= 6.f;
					} else {
						if (killer->GetWeapon()->GetWeaponType() == SMG_WEAPON) {
							dir *= 2.8f;
						} else if (killer->GetWeapon()->GetWeaponType() == SHOTGUN_WEAPON) {
							dir *= 4.5f;
						} else {
							dir *= 3.5f;
						}
					}
					corp->AddImpulse(dir);
				} else if (kt == KillTypeGrenade) {
					corp->AddImpulse(MakeVector3(0, 0, -4.f - SampleRandomFloat() * 4.f));
				}
				corp->AddImpulse(victim->GetVelocty() * 32.f);
				corpses.emplace_back(corp);

				if (corpses.size() > corpseHardLimit) {
					corpses.pop_front();
				} else if (corpses.size() > corpseSoftLimit) {
					RemoveInvisibleCorpses();
				}
			}

			// add chat message
			std::string s;
			s = ChatWindow::TeamColorMessage(killer->GetName(), killer->GetTeamId());

			std::string cause;
			bool isFriendlyFire = killer->GetTeamId() == victim->GetTeamId();
			if (killer == victim)
				isFriendlyFire = false;

			Weapon *w =
			  killer ? killer->GetWeapon() : nullptr; // only used in case of KillTypeWeapon
			switch (kt) {
				case KillTypeWeapon:
					switch (w ? w->GetWeaponType() : RIFLE_WEAPON) {
						case RIFLE_WEAPON: cause += _Tr("Client", "Rifle"); break;
						case SMG_WEAPON: cause += _Tr("Client", "SMG"); break;
						case SHOTGUN_WEAPON: cause += _Tr("Client", "Shotgun"); break;
					}
					break;
				case KillTypeFall:
					//! A cause of death shown in the kill feed.
					cause += _Tr("Client", "Fall");
					break;
				case KillTypeMelee:
					//! A cause of death shown in the kill feed.
					cause += _Tr("Client", "Melee");
					break;
				case KillTypeGrenade:
					cause += _Tr("Client", "Grenade");
					break;
				case KillTypeHeadshot:
					//! A cause of death shown in the kill feed.
					cause += _Tr("Client", "Headshot");
					break;
				case KillTypeTeamChange:
					//! A cause of death shown in the kill feed.
					cause += _Tr("Client", "Team Change");
					break;
				case KillTypeClassChange:
					//! A cause of death shown in the kill feed.
					cause += _Tr("Client", "Weapon Change");
					break;
				default:
					cause += "???";
					break;
			}

			s += " [";
			if (isFriendlyFire)
				s += ChatWindow::ColoredMessage(cause, MsgColorFriendlyFire);
			else if (killer == world->GetLocalPlayer() || victim == world->GetLocalPlayer())
				s += ChatWindow::ColoredMessage(cause, MsgColorGray);
			else
				s += cause;
			s += "] ";

			if (killer != victim) {
				s += ChatWindow::TeamColorMessage(victim->GetName(), victim->GetTeamId());
			}

			killfeedWindow->AddMessage(s);

			// log to netlog
			if (killer != victim) {
				NetLog("%s (%s) [%s] %s (%s)", killer->GetName().c_str(),
				       world->GetTeam(killer->GetTeamId()).name.c_str(), cause.c_str(),
				       victim->GetName().c_str(), world->GetTeam(victim->GetTeamId()).name.c_str());
			} else {
				NetLog("%s (%s) [%s]", killer->GetName().c_str(),
				       world->GetTeam(killer->GetTeamId()).name.c_str(), cause.c_str());
			}

			// show big message if player is involved
			if (victim != killer) {
				Player *local = world->GetLocalPlayer();
				if (killer == local || victim == local) {
					std::string msg;
					if (killer == local) {
						if ((int)cg_centerMessage == 2)
							msg = _Tr("Client", "You have killed {0}", victim->GetName());
					} else {
						msg = _Tr("Client", "You were killed by {0}", killer->GetName());
					}
					centerMessageView->AddMessage(msg);
				}
			}
		}
示例#26
0
/*
 * SmartCardContext.cpp
 *
 *  Created on: Aug 25, 2011
 *      Author: wladt
 */

#include <jq/pkcs11.hpp>
#include <jq/logger.hpp>

static const char_type
	*E_SC_PKCS11_LoadModule   = _Tr("unable to load PKCS11 module: %s"),
	*E_SC_PKCS11_GetFuncList  = _Tr("failed to retrieve 'C_GetFunctionList'"),
	*E_SC_PKCS11_ApiLoad      = _Tr("failed to obtain the table of PKCS11 API functions"),
	*E_SC_PKCS11_Initialize   = _Tr("failed to initialize PKCS11"),
	*E_SC_PKCS11_GetInfo      = _Tr("failed to get PKCS11 info"),
	*E_SC_PKCS11_SlotIndexOutOfBounds = _Tr("slot index is out of bounds"),
	*E_SC_PKSC11_SlotList     = _Tr("failed to get slot list"),
	*E_SC_PKCS11_SlotInfo     = _Tr("failed to get slot info"),
	*E_SC_PKCS11_OpenSession  = _Tr("failed to open session"),
	*E_SC_PKCS11_CloseSession = _Tr("unable to close session"),
	*E_SC_PKCS11_Login        = _Tr("login failed"),
	*E_SC_PKCS11_Logout       = _Tr("logout failed"),
	*E_SC_PKCS11_WaitSlot     = _Tr("waiting slot event failed");

JQ_NS_BEGIN

static const char* _ckrvToString(CK_RV res);

static void _set_pkcs11_error(CK_RV rv, const String& msg)
{