CUString FixFileNameString(const CUString& strIn) { int nLoc=0; int nOldPos=-1; CUString strRILC=g_config.GetRILC(); CUString strToTest(strIn); // Remove any trailing spaces strToTest.TrimLeft(); // Remove any leading spaces strToTest.TrimRight(); for ( nLoc=0; nLoc< ILLEGAL_FNAME_CHARS.GetLength() ; nLoc++) { int nPos=0; int nChar = 0x20; int nRes = swscanf(strRILC.Mid(nLoc*3,2), _W( "%2X" ), &nChar ); if ( ( EOF == nRes ) || ( 0 == nRes ) ) { nChar = 0x20; } while ( nPos < strToTest.GetLength() ) { if ( strToTest.GetAt( nPos ) == ILLEGAL_FNAME_CHARS[ nLoc ] ) { // nChar can be zero, if this is the case, we have to strip // the illegal character, and not replace it if ( nChar ) { // replace character strToTest.SetAt( nPos, (char)(nChar) ); // advance to next character nPos++; } else { // No replacement available, thus // delete the illegal character from the string strToTest= strToTest.Left(nPos) + strToTest.Right(strToTest.GetLength() - nPos - 1 ); } } else { // advance to next character nPos++; } } nPos = strToTest.GetLength() - 1 ; while ( nPos >= 0 ) { if ( '.' != strToTest.GetAt( nPos ) ) break; strToTest = strToTest.Left( strToTest.GetLength() -1 ); nPos--; } } return strToTest; }
void COpenFileDlg::AddRecursiveFiles( const CUString& strDir,int nItem ) { CFileFind fileFind; CUString pathAndFileType = strDir + CUString( _W( "\\*.*" )); BOOL bStop=FALSE; CUStringConvert strCnv; // Iterate through the items in the listbox and populate the listconrol. if (fileFind.FindFile( strCnv.ToT( pathAndFileType ) ) ) { do { bStop=(fileFind.FindNextFile()==0); CUString strFileName = CUString( fileFind.GetFileName() ); CUString strFileRoot = CUString( fileFind.GetRoot() ); CUString strFileType; if ( TRUE == fileFind.IsDirectory() && FALSE == fileFind.IsDots() && TRUE == m_bRecursiveDir ) { AddRecursiveFiles( strDir + CUString( _W( "\\" ) ) + strFileName, nItem ); } if (fileFind.IsDirectory()==FALSE && fileFind.IsDots()==FALSE) { int nPos=strFileName.ReverseFind( _T( '.' ) ); if (nPos>0) { CUString strExt; strExt = strFileName.Right(strFileName.GetLength()-nPos-1); strFileType = strExt; strExt.MakeUpper(); if ( CompareExt( strExt ) == TRUE ) { CUString strFileSize; CUString strFileDate; CTime fileTime; // Get the data/time stamp of this file fileFind.GetLastWriteTime( fileTime ); // Format date time string strFileDate.Format( _W( "%4d/%02d/%02d %02d:%02d" ), fileTime.GetYear(), fileTime.GetMonth(), fileTime.GetDay(), fileTime.GetHour(), fileTime.GetMinute() ); strFileSize.Format( _W( "%10.2f" ), fileFind.GetLength() / ( 1024.0 * 1024.0 ) ); CUStringConvert strCnv; m_ctrlRequestedFiles.InsertItem( nItem, strCnv.ToT( strFileName )); m_ctrlRequestedFiles.SetItemText( nItem, FILE_OPEN_TYPE, strCnv.ToT( strFileType ) ); m_ctrlRequestedFiles.SetItemText( nItem, FILE_OPEN_DATE ,strCnv.ToT( strFileDate ) ); m_ctrlRequestedFiles.SetItemText( nItem, FILE_OPEN_PATH, strCnv.ToT( strFileRoot ) ); m_ctrlRequestedFiles.SetItemText( nItem, FILE_OPEN_SIZE, strCnv.ToT( strFileSize ) ); m_ctrlRequestedFiles.SetItemData( nItem, (DWORD)fileTime.GetTime() ); nItem++; } } } } while (bStop!=TRUE); } m_bSortAscending=TRUE; }
bool cMapHandler::Load(const tString &asFile,const tString& asStartPos) { tString sMapName = cString::ToLowerCase(cString::SetFileExt(asFile,"")); cWorld3D *pWorld=NULL; cWorld3D *pLastMap = NULL; bool bFirstTime = false; double fTimeSinceVisit=0; #ifdef DEMO_VERSION glNumOfLoads++; if(glNumOfLoads > 5){ CreateMessageBoxW( _W("Demo not playable any more!\n"), _W("The limits of the demo have been exceeded!\n")); exit(0); } #endif unsigned long lStartTime = mpInit->mpGame->GetSystem()->GetLowLevel()->GetTime(); if(sMapName != msCurrentMap) { //////////////////////////////////////// // DESTRUCTION OF STUFF NOT SAVED ////// //remove all local timer //RemoveLocalTimers(); //Exit script if(mpScene->GetWorld3D()) { //OnMapLoad for all entities tGameEntityMapIt GIt = m_mapGameEntities.begin(); for(; GIt != m_mapGameEntities.end(); ++GIt) { iGameEntity *pEntity = GIt->second; pEntity->OnWorldExit(); } mpScene->GetWorld3D()->GetScript()->Run("OnExit()"); pLastMap = mpScene->GetWorld3D(); } mpInit->mpMusicHandler->OnWorldExit(); //Destroy the player objects so they are no saved. mpInit->mpPlayer->OnWorldExit(); mpInit->mpPlayerHands->OnWorldExit(); mpInit->mpGameMessageHandler->OnWorldExit(); //////////////////////////////////////// // SAVING ///////////////////////////// //Save the map if(msCurrentMap != "" && mpScene->GetWorld3D() != NULL) { mpInit->mpSaveHandler->SaveData(msCurrentMap); } msCurrentMap = sMapName; //////////////////////////////////////// // DESTRUCTION OF SAVED STUFF ////////// mpInit->mpInventory->ClearCallbacks(); //Reset the rendering. mpInit->mpGame->GetGraphics()->GetRenderer3D()->SetAmbientColor(cColor(0,1)); mpInit->mpGame->GetGraphics()->GetRenderer3D()->SetSkyBoxActive(false); mpInit->mpGame->GetGraphics()->GetRenderer3D()->SetFogActive(false); //Remove all current objects mpInit->mbDestroyGraphics =false; DestroyAll(); mpInit->mbDestroyGraphics =true; //Destroy all sound entities on previous map. if(mpScene->GetWorld3D()) { mpScene->GetWorld3D()->DestroyAllSoundEntities(); } mpInit->mpPlayer->ClearCollideScripts(); //Stop all sound mpInit->mpGame->GetSound()->GetSoundHandler()->StopAll(eSoundDest_World); mpInit->mpGame->GetSound()->Update(1.0f/60.0f); //Destroy Haptic shapes if(mpInit->mbHasHaptics) mpInit->mpGame->GetHaptic()->GetLowLevel()->DestroyAllShapes(); //////////////////////////////////////// // LOAD THE MAP //////////////////////// //Load if(mpScene->HasLoadedWorld(asFile)) { //Log("-------- Loaded NOT first time! ----------------\n"); pWorld = mpScene->LoadWorld3D(asFile,true, eWorldLoadFlag_NoGameEntities); //eWorldLoadFlag_NoLights | //eWorldLoadFlag_NoEntities | //eWorldLoadFlag_NoGameEntities); if(pWorld) mpScene->SetWorld3D(pWorld); else { Error("Couldn't load map '%s'\n",asFile.c_str()); return false; } mpInit->mpSaveHandler->LoadData(msCurrentMap); mpInit->mpGame->GetResources()->GetSoundManager()->DestroyUnused(mpInit->mlMaxSoundDataNum); mpInit->mpGame->GetResources()->GetParticleManager()->DestroyUnused(mpInit->mlMaxPSDataNum); } else { //Log("-------- FIRST TIME first time! ----------------\n"); pWorld = mpScene->LoadWorld3D(asFile,true,0); mpInit->mpGame->GetResources()->GetSoundManager()->DestroyUnused(mpInit->mlMaxSoundDataNum); mpInit->mpGame->GetResources()->GetParticleManager()->DestroyUnused(mpInit->mlMaxPSDataNum); if(pWorld) mpScene->SetWorld3D(pWorld); else { Error("Couldn't load map '%s'\n",asFile.c_str()); return false; } bFirstTime = true; } /////////////////////////// //Add to cache mpWorldCache->DecResources(); mpWorldCache->AddResources(); /////////////////////////// //Destroy old map if(pLastMap) { mpScene->DestroyWorld3D(pLastMap); } fTimeSinceVisit = AddLoadedMap(pWorld); pWorld->GetPhysicsWorld()->SetMaxTimeStep(mpInit->mfMaxPhysicsTimeStep); //OnMapLoad for all entities tGameEntityMapIt GIt = m_mapGameEntities.begin(); for(; GIt != m_mapGameEntities.end(); ++GIt) { iGameEntity *pEntity = GIt->second; pEntity->OnWorldLoad(); } //OnMapLoad for player mpInit->mpPlayer->OnWorldLoad(); mpInit->mpPlayerHands->OnWorldLoad(); mpInit->mpMusicHandler->OnWorldLoad(); if(bFirstTime) { //Set a default name msMapGameName = cString::To16Char(cString::SetFileExt(asFile,"")); //Init script if(pWorld->GetScript()) pWorld->GetScript()->Run("OnStart()"); } } else { if(mpScene->GetWorld3D() != NULL) { pWorld = mpScene->GetWorld3D(); } else { Error("No world has been loaded!\n"); return false; } } mpInit->mpPlayer->SetStartPos(asStartPos); //Run global script if(mpInit->mpGlobalScript) { if(bFirstTime) mpInit->mpGlobalScript->Run("OnMapStart()"); mpInit->mpGlobalScript->Run("OnMapLoad()"); } if(pWorld->GetScript()) { pWorld->GetScript()->Run("OnLoad()"); } //After script has been run callback tGameEntityMapIt GIt = m_mapGameEntities.begin(); for(; GIt != m_mapGameEntities.end(); ++GIt) { iGameEntity *pEntity = GIt->second; pEntity->OnPostLoadScripts(); } //Log("After load and before preupdate:\n"); unsigned long lTime = mpInit->mpGame->GetSystem()->GetLowLevel()->GetTime() - lStartTime; Log("Loading map '%s' took: %d ms\n",pWorld->GetFileName().c_str(),lTime); PreUpdate(fTimeSinceVisit); mpInit->mpGame->ResetLogicTimer(); //mpInit->mpGame->GetSound()->GetSoundHandler()->ResumeAll(eSoundDest_World | eSoundDest_Gui); //Log("After load and preupdate:\n"); //Set physics accuracy pWorld->GetPhysicsWorld()->SetAccuracyLevel(mpInit->mPhysicsAccuracy); return true; }
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; }
// Error report function void CHyperLink::ReportError(int nError) { CUString str; switch (nError) { case 0: str = _W("The operating system is out\nof memory or resources."); break; case ERROR_FILE_NOT_FOUND: str = _W("The specified file was not found."); break; case ERROR_PATH_NOT_FOUND: str = _W("The specified path was not found."); break; case ERROR_BAD_FORMAT: str = _W("The .EXE file is invalid\n(non-Win32 .EXE or error in .EXE image)."); break; case SE_ERR_ACCESSDENIED: str = _W("The operating system denied\naccess to the specified file."); break; case SE_ERR_ASSOCINCOMPLETE: str = _W("The filename association is\nincomplete or invalid."); break; case SE_ERR_DDEBUSY: str = _W("The DDE transaction could not\nbe completed because other DDE transactions\nwere being processed."); break; case SE_ERR_DDEFAIL: str = _W("The DDE transaction failed."); break; case SE_ERR_DDETIMEOUT: str = _W("The DDE transaction could not\nbe completed because the request timed out."); break; case SE_ERR_DLLNOTFOUND: str = _W("The specified dynamic-link library was not found."); break; //case SE_ERR_FNF: str = _W("Windows 95 only: The specified file was not found."); break; case SE_ERR_NOASSOC: str = _W("There is no application associated\nwith the given filename extension."); break; case SE_ERR_OOM: str = _W("There was not enough memory to complete the operation."); break; //case SE_ERR_PNF: str = _T("The specified path was not found."); break; case SE_ERR_SHARE: str = _W("A sharing violation occurred. "); break; default: str.Format(_W("Unknown Error (%d) occurred."), nError); break; } str = _W( "Can't open link:\n\n" ) + str; CDexMessageBox( str, MB_ICONEXCLAMATION | MB_OK); }
//------------------------------------------ bool CEngine::Initialize(const wchar* settings/*="game.ini"*/, bool customWindow/*=false*/, sDisplayProperties *dp/*=NULL*/){ assertd(s_bInit==false, "DOUBLE ENGINE INITIALIZATION!"); s_bInit = true; //predict :-P // initialize random generator srand( (unsigned int)milisec() ); cInternalWindow()->BeginSplash(); // memory leaks detection #if defined(_DEBUG) && defined(_MSC_VER) && _MSC_VER >= 800 _CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF ); //_CrtSetBreakAlloc(23296); #endif // --------------------------------------------------- // QUEUE TESTS CON(MSG_INFO, _W("------- Command Queue Test -------")); CCommandQueue q; DWORD tim; for (int t=0; t<10; t++) { tim = GetTickCount(); // FILL IN QUEUE for (int i=0; i<20000; i++) { sE2RCanvasDesc *cd; q.Enqueue(NULL, CQI_ENGINE2RENDERER_CANVAS_CREATE, (void*&)cd, sizeof(sE2RCanvasDesc)); cd->handle = 0; } CON(MSG_INFO, _W("Iteration #%d: Enqueue %d ms"), t, GetTickCount()-tim ); // DEQUEUE unsigned int cqi; const void* optr; IQueueCommandReceiver *recv; tim = GetTickCount(); while (q.Dequeue(cqi, optr, recv)) { switch(cqi) { case CQI_ENGINE2RENDERER_CANVAS_CREATE: { sE2RCanvasDesc *cd = (sE2RCanvasDesc *)optr; } break; } } CON(MSG_INFO, _W("Iteration #%d: Dequeue %d ms"), t, GetTickCount()-tim ); } CON(MSG_INFO, _W("----------------------------------")); // --------------------------------------------------- // --- WRITE INFO ABOUT LIBRARIES AND MODULES I_DebugPrint( ConsoleMsg ); CON(MSG_INFO, _W("= %s %s build %d initialization ="), _W(P3DNAME), sizeof(void*)==8?_W("x64"):_W("x86"), GetBuildNum()); if (sizeof(wchar)>1) CON(MSG_INFO, _W("Unicode support \x263A")); else CON(MSG_INFO, _W("Multibyte character set")); // --- LOAD SETTINGS m_szSettings = new wchar[wstrlen(settings)+1]; wstrcpy(m_szSettings, settings); cConfig()->Load(m_szSettings); //cConfig()->Save(m_szSettings); // --- INITIALIZE SCRIPT SYSTEM CON(MSG_INFO, _W("Script system initialization")); cScriptEngine()->Initialize(); // --- LOAD KEY BINDINGS cInputManager()->Assign(_W("GUI_CURSOR"), WE_MOUSE_MOTION, 0); cInputManager()->Assign(_W("GUI_SELECT"), WE_MOUSE_DOWN, 0); cInputManager()->Save(_W("keys.ini")); // TODO: FIXME: What about load? :D // --- CREATE MAIN WINDOW Vec2i mainWindowSize(800,600); bool initFullscreen = false; if (customWindow) { // use primary screen resolution for frame buffer // TODO: multiplatform #ifdef _WIN32 mainWindowSize.x = GetSystemMetrics(SM_CXSCREEN); mainWindowSize.y = GetSystemMetrics(SM_CYSCREEN); #endif } else { if (dp) { // use user-defined resolution initFullscreen = dp->Fullscreen; mainWindowSize.x = dp->HorRes; mainWindowSize.y = dp->VertRes; } else { // use settings initFullscreen = svFullscreen.GetBool(); mainWindowSize.x = svResolutionX.GetInt(); mainWindowSize.y = svResolutionY.GetInt(); } } cInternalWindow()->Create(mainWindowSize); //Init the internal input system cInternalInput()->Init( cInternalWindow()->GetHandle() ); //Init the Filesystem cFilesystem()->Init(); // --- LOAD SELECTED MODULES s_pRenderer = (IRenderer*)I_GetModule(_W("renderer"), svRenderer.GetString()); if (!s_pRenderer) CON(MSG_ERR_FATAL, _W("Cannot load renderer module. It is a core module, cannot continue!")); s_pSound = (ISoundEngine*)I_GetModule(_W("sound"), svSound.GetString()); if (!s_pSound) CON(MSG_ERR_FATAL, _W("Cannot load sound module. It is a core module, cannot continue!")); s_pPhys = (IPhysEngine*)I_GetModule(_W("physics"), svPhysics.GetString()); if (!s_pPhys) CON(MSG_ERR_FATAL, _W("Cannot load phys module. It is a core module, cannot continue!")); s_pFS = (IFileSystem*)I_GetModule(_W("filesystem"), svFileSystem.GetString()); if (!s_pFS) CON(MSG_ERR_FATAL, _W("Cannot load filesystem module. It is a core module, cannot continue!")); s_pGUI = (IGUI*)I_GetModule(_W("gui"), svGUI.GetString()); if (!s_pGUI) CON(MSG_ERR_FATAL, _W("Cannot load GUI module. It is a core module, cannot continue!")); m_bModulesLoaded=true; // ==== INITIALIZE MODULES ==== s_pRenderer->Initialize(this, &m_queueRenderer); bool ret = s_pRenderer->iGraphicsDevice()->Initialize(mainWindowSize.x, mainWindowSize.y, initFullscreen, cInternalWindow()->GetHandle()); if (!ret) { CON(MSG_ERR_FATAL, _W("Failed to initialize graphics device!")); } // ===== SERIALIZATION DEBUG AND TEST ======= Scene scene; //scene.Save(s_pFS, _W("scenes/test.robject"), iConsole()); //CModel model; /*model = (Model*)cObjectManager()->CreateObject( _W("Model") ); MeshData md; MeshSubset ms; // Material m; // ms.Material = m; ms.NumTriangles = 1; ms.StartIndex = 0; //ms.StartVertex = 0; md.Subsets.AddEx(ms); md.Indices.AddEx(0); md.Indices.AddEx(1); md.Indices.AddEx(2); md.NumIndices = 3; MeshVertexData mvd; mvd.Usage = _W("P3DVU_POSITION"); mvd.DataSize = 3; mvd.Float3.AddEx(Vec3Param(0.0f, 0.0f, 0.0f)); mvd.Float3.AddEx(Vec3Param(0.0f, 1.0f, 0.0f)); mvd.Float3.AddEx(Vec3Param(1.0f, 1.0f , 0.0f)); md.DataStreams.AddEx(mvd); md.NumVerts = 3; model->LODs.AddEx(md); model->Save(s_pFS, _W("triangle.robject"), iConsole()); model->PreCache();*/ // =========================================== bool initOK=true; initOK &= s_pSound->Initialize(this); initOK &= s_pPhys->Initialize(this); initOK &= s_pFS->Initialize(this); initOK &= s_pGUI->Initialize(this); if (!initOK) CON(MSG_ERR_FATAL, _W("Failed to initialize some core module(s)! Cannot continue. For more details see console.htm.")); cSceneManager()->Create(); cConsole()->InitializeGUI(); // at this time, coz it uses GUI module and it must be initialized ;) // FIXME: register engine to script, temporary here /*using namespace luabind; lua_State* L = cScriptEngine()->GetLVM(); module(L) [ class_<CEngine>("Engine") .scope [ def("GetBuildNum", &CEngine::GetBuildNum ) ] ];*/ // load bootstrap script cScriptEngine()->LoadScript(_W("scripts/bootstrap.rscript")); // DEBUG TESTING OF QUEUE TO RENDERER sE2RCanvasDesc* canvas; EnqueueMessage( MC_RENDERER, this, CQI_ENGINE2RENDERER_CANVAS_CREATE, (void*&)canvas, sizeof(sE2RCanvasDesc) ); canvas->handle = cInternalWindow()->GetHandle(); canvas->size = Vec2i(800,600); canvas->windowed = !initFullscreen; //Sleep(10000); cInternalWindow()->EndSplash(); cInternalWindow()->SetVisible(true); //Filesystem test /*UINT oSize; void *lData=0; if(cFilesystem()->Load(_W("scripts.bootstrap"), &lData, oSize)==P3D_FILERESULT_OK) cFilesystem()->FreeLoadedData(lData); const char* testStr = "this is a test string"; cFilesystem()->Save(_W("scripts.fstest"), testStr, sizeof(char)*strlen(testStr));*/ return true; }
void CLanguage::ParseLanguageFile( const CUString& strFileName ) { BOOL bResult = TRUE; DWORD dwRevision = 0; FILE* pFile = NULL; CUString strFullFileName = m_strLanguageDir + _W("\\lang\\") + strFileName + m_strLangFileExt; CUStringConvert strCnv; pFile = CDexOpenFile( strFullFileName, _W( "r" ) ); if ( NULL != pFile ) { CHAR lpszRead[ 1024 ]; int nStart = 0; int nStop = 0; CUString strRead; memset( lpszRead, 0, sizeof( lpszRead ) ); while ( fgets( lpszRead, sizeof( lpszRead ), pFile ) ) { bool bHasNumber = false; bool bIsMenu = false; bool bIsDialog = false; bool bHasString = false; DWORD nIndex = 0; CLangElement newElement; strRead = _T( "" ); for ( nIndex = 0; nIndex< strlen( lpszRead ); nIndex++ ) { if ( ( lpszRead[ nIndex ] != 0x0A ) && ( lpszRead[ nIndex ] != 0x0D ) ) { strRead += (TCHAR)lpszRead[ nIndex ]; } } TranslateTab( strRead ); nStart = strRead.Find( _T( '#' ) ); if ( nStart >= 0 ) { if ( ( nStart + 1 ) == strRead.Find( _T( 'M' ) ) ) { nStart++; bIsMenu = TRUE; } else if ( ( nStart + 1 ) == strRead.Find( _T( 'D' ) ) ) { nStart++; bIsDialog = TRUE; } nStop = strRead.Find( _T( '#' ), nStart + 1 ); if ( nStop > 2 ) { CUString strID ( strRead.Mid( nStart + 1, nStop - nStart -1 ) ); swscanf( strID, _W( "%x" ), &newElement.nID ); bHasNumber = true; } } else { if ( strRead.Find( CODEPAGETAG ) == 0 ) { m_dwCodePageID = _wtoi( strRead.Mid( CODEPAGETAG.GetLength() ) ); } else if ( strRead.Find( LANGTAG ) == 0 ) { m_dwLangID = _wtoi( strRead.Mid( LANGTAG.GetLength() ) ); } else if ( strRead.Find( SUBLANGTAG ) == 0 ) { m_dwSubLangID = _wtoi( strRead.Mid( SUBLANGTAG.GetLength() ) ); } else if ( strRead.Find( REVISIONTAG ) == 0 ) { int nPos; nPos = strRead.Find( _W( ",v " ) ); if ( nPos >= 0 ) { float fVersion = 1.0f; swscanf( strRead.Mid( nPos+3,4 ), _W( "%f" ), &fVersion ); dwRevision = (DWORD)( 100 * ( fVersion + 0.005 ) ); } } } nStart = strRead.Find( '"' ); if ( nStart >= 0 ) { nStop = strRead.Find( '"', nStart + 1 ); if ( nStop > 2 ) { lpszRead[ 0 ] = '\0'; for ( nIndex = nStart + 1; nIndex < (DWORD)nStop; nIndex++) { lpszRead[ nIndex - nStart - 1] = (CHAR)strRead.GetAt( nIndex ); lpszRead[ nIndex - nStart ] = '\0'; } newElement.strValue = CUString( lpszRead, m_dwCodePageID ); bHasString = true; } } if ( bHasString && bHasNumber ) { if ( bIsMenu ) { m_vMenus.push_back( newElement ); } else if ( bIsDialog ) { m_vDialogs.push_back( newElement ); } else { m_vStrings.push_back( newElement ); } } memset( lpszRead, 0, sizeof( lpszRead ) ); } fclose( pFile ); } #ifdef UNICODE TCHAR* pTest = _wsetlocale( LC_ALL, GetString( 99 ) ); #else TCHAR* pTest = setlocale( LC_ALL, strCnv.ToT( GetString( 99 ) ) ); #endif SetThreadLocale( MAKELCID( m_dwLangID, m_dwSubLangID ) ); setlocale( LC_NUMERIC, "English" ); }
std::string OsirisLink::generate() const { #ifdef OS_OSIRIS_VERSION_RAZOR bool newFormat = true; #else bool newFormat = false; #endif if(isValid() == false) return ""; if(hasParam("type") == false) return ""; if(newFormat) { std::string out = ""; for(OsirisLinkParams::const_iterator i = m_params.begin(); i != m_params.end(); ++i) { std::string key = i->first; std::wstring value = i->second; if(key != "type") // Type forced below, simply to ensure it's the first. { if(value != _W("")) { out += "&" + key + "=" + HttpParser::urlEncodeW(value); } } } return "osiris:?type=" + HttpParser::urlEncodeW(getParam("type")) + out; } else { if(getParam("type") == OS_OSIRISLINK_TYPE_PORTAL) { if(hasParam("portal") == false) return ""; std::string out = "osiris://|portal|" + HttpParser::urlEncodeW(getParam("portal")) + "|"; if(hasParam("name")) out += "name=" + HttpParser::urlEncodeW(getParam("name")) + "|"; if(hasParam("description")) out += "description=" + HttpParser::urlEncodeW(getParam("description")) + "|"; if(hasParam("user")) out += "user="******"010000002") + getParam("pov")) + "|"; return out; } else if(getParam("type") == OS_OSIRISLINK_TYPE_ISIS) { if(hasParam("portal") == false) return ""; std::string out = "osiris://|isis|" + HttpParser::urlEncodeW(getParam("portal")) + "|"; if(hasParam("name")) out += "name=" + HttpParser::urlEncodeW(getParam("name")) + "|"; if(hasParam("url")) out += "url=" + HttpParser::urlEncodeW(getParam("url")) + "|"; return out; } else if(getParam("type") == OS_OSIRISLINK_TYPE_FILE) { std::string out = "osiris://|file|" + HttpParser::urlEncodeW(getParam("id")) + "|"; return out; } else if(getParam("type") == OS_OSIRISLINK_TYPE_URL) { std::wstring url = getParam("url"); StringVector array1; utils::split(url, _S("?"), array1); std::wstring params = _W(""); if(array1.size()>=2) { url = array1[0].to_wide(); params = array1[1].to_wide(); } if(hasParam("portal")) { if(params.empty() == false) params += _W("&"); params += _W("portal=") + getParam("portal"); } /* std::string out = "osiris://|url|" + HttpParser::urlEncodeW(url) + "|"; if(params != _W("")) out += HttpParser::urlEncodeW(params) + "|"; */ std::string out = "osiris://|url|" + utils::wtoa(url) + "|"; if(params != _W("")) out += utils::wtoa(params) + "|"; return out; } else if(getParam("type") == OS_OSIRISLINK_TYPE_RES) { std::string out = "osiris://|skin|" + HttpParser::urlEncodeW(getParam("path")) + "|"; return out; } else { return ""; } } }
void OsirisLink::setParam(const std::string &name, const std::wstring &value) { if(value != _W("")) m_params[name] = value; }
//--------------------------------------------------------------------------- CFS_Sqlite::~CFS_Sqlite() { CON(MSG_INFO, _W("Database filesystem sqlite shutdown") ); sqlite3_shutdown(); }
bool OsirisLink::parse(const std::string &link) { if(link.empty()) return false; if(link.substr(0,9) == "osiris://") { // Old format // Compatibility problem: Firefox encode the | std::string link2 = link; algorithms::replace_all(link2, "%7C", "|"); StringVector array1; utils::split(link2, _S("|"), array1); if(array1.size()<2) return false; std::wstring type = array1[1].to_wide(); if( (type == OS_OSIRISLINK_TYPE_PORTAL) || (type == OS_OSIRISLINK_TYPE_ISIS) ) { if(array1.size() < 4) return false; setParam("type", type); setParam("portal", array1[2].to_wide()); for(uint32 i=3;i<array1.size();i++) { std::string part = array1[i].to_ascii(); StringVector array2; utils::split(part, _S("="), array2); std::string paramKey; std::wstring paramValue; if(array2.size()>=1) paramKey = array2[0].to_ascii(); if(array2.size()>=2) paramValue = HttpParser::urlDecodeW(array2[1].to_ascii()); if( (paramKey != "") && (paramValue != _W("")) ) setParam(paramKey, paramValue); } } else if(type == OS_OSIRISLINK_TYPE_FILE) { if(array1.size() != 3) return false; setParam("type", OS_OSIRISLINK_TYPE_FILE); setParam("id", array1[2].to_wide()); } else if(type == OS_OSIRISLINK_TYPE_URL) { if(array1.size() <= 2) return false; std::wstring url; std::wstring params; if(array1.size() > 2) url = HttpParser::urlDecodeW(array1[2].to_ascii()); if(array1.size() > 3) { params = HttpParser::urlDecodeW(array1[3].to_ascii()); int nParamsFound = 0; StringVector arrayP; utils::split(params,_S("&"), arrayP); for(uint32 a1=0; a1 < arrayP.size(); a1++) { StringVector array2; utils::split(arrayP[a1],_S("="), array2); std::wstring paramKey; std::wstring paramValue; if(array2.size()>=1) paramKey = HttpParser::urlDecodeW(array2[0].to_ascii()); if(array2.size()>=2) paramValue = HttpParser::urlDecodeW(array2[1].to_ascii()); if( (paramKey != "") && (paramValue != _W("")) ) { if(paramKey == _W("portal")) { setParam("portal", paramValue); } else { if(nParamsFound == 0) url += _W("?"); nParamsFound++; url += utils::atow(HttpParser::urlEncodeW(paramKey)); url += _W("="); url += utils::atow(HttpParser::urlEncodeW(paramValue)); } } } } setParam("type", OS_OSIRISLINK_TYPE_URL); setParam("url",url); } else if(type == _W("skin")) { if(array1.size() != 3) return false; setParam("type", OS_OSIRISLINK_TYPE_RES); setParam("path", array1[2].to_wide()); } else return false; // Conversion of old 0.X portal ID String oldPortalID = getParam("portal"); if(oldPortalID.empty() == false) setParam("portal", CryptManager:: instance()->SHA(oldPortalID.buffer(), oldPortalID.buffer_size()).toHex()); } else if(link.substr(0,8) == "osiris:?") { std::string params = link.substr(8); StringVector array1; utils::split(params,_S("&"), array1); for(uint32 a1=0; a1 < array1.size(); a1++) { StringVector array2; utils::split(array1[a1],_S("="), array2); std::string paramKey; std::wstring paramValue; if(array2.size()>=1) paramKey = array2[0].to_ascii(); if(array2.size()>=1) paramValue = HttpParser::urlDecodeW(array2[1].to_ascii()); if( (paramKey != "") && (paramValue != _W("")) ) setParam(paramKey, paramValue); } } else return false; return isValid(); }
bool SearchDownValues(var &result, var head, var body) { std::map<Var,def_t>::const_iterator iter = DownValues.find(head); if(iter != DownValues.end()) { const def_t &definitions = iter->second; if (Verbose >= 2) { wcerr << _W("Search downvalue for "); Println(Ex(head, body), wcerr); } if (definitions.is_vec()) { def_t::vec_t::const_iterator iter2 = definitions.vec->begin(); while(iter2 != definitions.vec->end()) { if (Verbose >= 2) { wcerr << _W("# Try "); Print(iter2->first); wcerr << _W(" :> "); Print(iter2->second.second); wcerr << std::endl; } map_t m; if(MatchQ(m,iter2->second.first,body)) { if (TraceRuleSymbols.count(head) != 0) { // FIXME: rewrite this after we implement the kernel message infrastructure Print(head); wcout << _W("::tracer : "); Print(Ex(head, body)); wcout << _W(" :> "); Print(iter2->second.second); wcout << "\n"; } result = Eval(Subs(m,iter2->second.second)); if (ExQ(result, TAG(Condition))) { ++iter2; continue; } if (Verbose >= 2) { wcerr << _W("Result is "); Println(result, wcerr); } return true; } ++iter2; } } else { def_t::map_t::const_iterator iter2 = definitions.map->begin(); if (Verbose >= 2) { wcerr << _W("Search downvalue for "); Println(Ex(head, body), wcerr); } while(iter2 != definitions.map->end()) { if (Verbose >= 2) { wcerr << _W("# Try "); Print(iter2->first); wcout << _W(" :> "); Print(iter2->second.second); wcout << std::endl; } map_t m; if(MatchQ(m,iter2->second.first,body)) { if (TraceRuleSymbols.count(head) != 0) { // FIXME: rewrite this after we implement the kernel message infrastructure Print(head); wcout << _W("::tracer : "); Print(Ex(head, body)); wcout << _W(" :> "); Print(iter2->second.second); wcout << "\n"; } result = Eval(Subs(m,iter2->second.second)); if (ExQ(result, TAG(Condition))) { ++iter2; continue; } if (Verbose >= 2) { wcerr << _W("Result is "); Println(result, wcerr); } return true; } ++iter2; } } } return false; }
namespace portal { ////////////////////////////////////////////////////////////////////// const std::wstring ObjectDetail::ID = _W("id"); ////////////////////////////////////////////////////////////////////// ObjectDetail::ObjectDetail(shared_ptr<HttpSession> session) : PageBase(session) { } ObjectDetail::~ObjectDetail() { } String ObjectDetail::getUrlID() const { return getRequest()->getUrlParam(ID); } String ObjectDetail::getPageName() const { return _S("portal.pages.objectDetail"); } void ObjectDetail::onLoad() { PageBase::onLoad(); // Ottiene l'id dell'utente richiesto EntityID id = getUrlID().to_ascii(); shared_ptr<XMLDocument> document(OS_NEW XMLDocument()); shared_ptr<XMLNode> nodeRoot = document->create(_S("object")); shared_ptr<EntitiesEntity> entity = getPortal()->getEntity(getDatabase(), id); if(entity != nullptr) { shared_ptr<XMLPortalExporter> exporter(OS_NEW XMLPortalExporter(nodeRoot, get_this_ptr<IPortalPage>(), XMLPortalExporter::emFull, true)); entity->exportXML(exporter); } String path = getSkin()->getTemplatePath(_S("object_detail.xsl")); shared_ptr<HtmlXSLControl> pageTemplate(OS_NEW HtmlXSLControl(loadStylesheet(path), document)); // Carica il template di riferimento getControls()->add(pageTemplate); } void ObjectDetail::onPreRender() { PageBase::onPreRender(); } ////////////////////////////////////////////////////////////////////// } // portal
CUString FormatTrackNameString( CUString strFormat, ENUM_FILENAME_CONVERTS nType ) { int i; switch ( nType ) { case FILENAME_CONVERT_NONE: // do noting break; case FILENAME_CONVERT_LOWER: strFormat.MakeLower(); break; case FILENAME_CONVERT_UPPER: strFormat.MakeUpper(); break; case FILENAME_CONVERT_FC_UPPER: strFormat.MakeLower(); if ( strFormat.GetLength() > 0 ) { CUString strTmp( strFormat.Left( 1 ) ); strTmp.MakeUpper(); strFormat.SetAt( 0, strTmp.GetAt( 0 ) ); } break; case FILENAME_CONVERT_FCEW_UPPER: strFormat.MakeLower(); for ( i=0; i < strFormat.GetLength()-1; i++ ) { if ( i == 0 ) { CUString strTmp( strFormat.Mid( 0, 1 ) ); strTmp.MakeUpper(); strFormat.SetAt( 0, strTmp.GetAt( 0 ) ); } else { if ( ( 0 == _istalnum( strFormat.GetAt( i ) ) ) && ( _T( '\'' ) != strFormat.GetAt( i ) ) ) { CUString strTmp( strFormat.Mid( i+1, 1 ) ); strTmp.MakeUpper(); strFormat.SetAt( i+1, strTmp.GetAt( 0 ) ); } } } break; case FILENAME_CONVERT_SWAP_ARTIST_TRACK: i = strFormat.Find( _W( " / " ) ); if ( i > 0 ) { CUString str1; CUString str2; str1 = strFormat.Left( i ); str2 = strFormat.Mid( i + 3 ); strFormat = str2 + _W( " / " ) + str1; } break; default: ASSERT( FALSE ); } return strFormat; }
UINT CCDPlayDigital::RipAndPlay( PVOID pParams ) { CDEX_ERR bReturn = CDEX_OK; long nBufferSize = 0; BOOL bPause = FALSE; // tracing info ENTRY_TRACE( _T( "CCDPlayDigital::RipAndPlay" ) ); // get pointer to active CCDPlayDigital object CCDPlayDigital* pParent= (CCDPlayDigital*)pParams ; pParent->m_bAbort = FALSE; auto_ptr<PlayWavStream> pPlayStream( new PlayWavStream ); if ( NULL == pPlayStream.get() ) { bReturn = CDEX_ERROR; } else { pPlayStream->SetSampleRate( 44100 ); pPlayStream->SetChannels( 2 ); pPlayStream->SetBytesPerSample( sizeof( SHORT ) ); } // Initialize play stream object if ( FALSE == pPlayStream->OpenStream( _W("") ) ) { bReturn = CDEX_ERROR; } else { } DWORD dwSampleBufferSize = pPlayStream->GetBufferSize() / sizeof( SHORT ); if ( CDEX_OK == bReturn ) { bReturn = CR_OpenRipper( &nBufferSize, pParent->GetBeginSector(), pParent->GetEndSector(), FALSE ); } if ( CDEX_OK == bReturn ) { LONG nNumBytesRead = 0; LONG nOffset = 0; // create the stream buffer, allocate on enocder frame additional memory auto_ptr<BYTE> pbtBufferStream( new BYTE[ nBufferSize + pPlayStream->GetBufferSize() + 16383 ] ); // Get a pointer to the buffer BYTE* pbtStream = pbtBufferStream.get(); CDEX_ERR ripErr; // Read all chunks while ( ( CDEX_RIPPING_DONE != ( ripErr = CR_RipChunk( pbtStream + nOffset, &nNumBytesRead, (BOOL&)pParent->m_bAbort ) ) ) && !*(volatile BOOL*)&pParent->m_bAbort ) { SHORT* psEncodeStream=(SHORT*)pbtStream; DWORD dwSamplesToConvert= ( nNumBytesRead + nOffset ) / sizeof( SHORT ); while ( pParent->m_bPause ) { if ( FALSE == bPause ) { pParent->m_dwCurrentTime = 0; pParent->m_dwSeekTimeOffset = pPlayStream->GetCurrentTime(); bPause = TRUE; pPlayStream->Pause(); } ::Sleep( 10 ); } if ( bPause ) { pPlayStream->Resume(); bPause = FALSE; } // Check for jitter errors if ( CDEX_JITTER_ERROR == ripErr ) { } // Check if an error did occur if ( CDEX_ERROR == ripErr ) { LTRACE( _T( "RipToEncoder::CDEX_ERROR" ) ); break; } // Get progress indication //nPercent = CR_GetPercentCompleted(); // Get relative jitter position // nJitterPos = CR_GetJitterPosition(); // Get the number of jitter errors // nJitterErrors = CR_GetNumberOfJitterErrors(); // Get the Peak Value // nPeakValue = CR_GetPeakValue(); // Convert the samples with the encoder while ( dwSamplesToConvert >= dwSampleBufferSize ) { if( FALSE == pPlayStream->Write( (BYTE*)psEncodeStream, dwSampleBufferSize * sizeof( SHORT ) ) ) { pParent->m_bAbort = TRUE; bReturn = CDEX_ERROR; } pParent->m_dwCurrentTime = pPlayStream->GetCurrentTime(); pParent->m_dwBytesWritten += dwSampleBufferSize * sizeof( SHORT ); // Decrease the number of samples to convert dwSamplesToConvert -= dwSampleBufferSize; // Increase the sample buffer pointer psEncodeStream += dwSampleBufferSize; } // Copy the remaing bytes up front, if necessary if ( dwSamplesToConvert > 0 ) { // Calculate the offset in bytes nOffset = dwSamplesToConvert * sizeof( SHORT ); // Copy up front memcpy( pbtStream, psEncodeStream, nOffset ); } else { nOffset = 0; } } // stop as quickly as possible on when aborting if ( pParent->m_bAbort ) { pPlayStream->Pause(); pPlayStream->Stop(); } else { if ( nOffset && pParent->m_bAbort ) { if( FALSE == pPlayStream->Write( pbtStream, nOffset ) ) { bReturn = CDEX_ERROR; } pParent->m_dwBytesWritten += nOffset; } LTRACE( _T( "Wait for player to Finish" ) ); } // Close the WAV player pPlayStream->CloseStream(); LTRACE( _T( "Player finished" ) ); // Close the Ripper session CR_CloseRipper( NULL ); } else { ASSERT( FALSE ); } pParent->m_pThread = NULL; pParent->m_bIsPlaying = FALSE; EXIT_TRACE( _T( "RipAndPlay" ) ); return bReturn; }
void FeedViewer::onLoad() { ViewerBase::onLoad(); shared_ptr<XMLNode> root = getModuleDocument()->getRoot(); OS_ASSERT(root != nullptr); // Ajax: // - Creo un controllo per contenere quanto sotto // - Chiamo un "isDirect" a livello di ModuleViewer, che restituisce un "true" se son puntato diretto. // - Se si, leggo il parametro "mode", se è "direct" restituisco il contenuto del controllo secco via transmit-buffer // - Qui dumpo una chiamata ad ajax passandogli l'url di me in direct mode String mode = _S("direct"); // Proprietà? mode = _S("ajax"); shared_ptr<HtmlDiv> divData(OS_NEW HtmlDiv()); String controlID = getInstance().toUTF16(); if(controlID.empty()) { controlID = _S("preview"); // Se il modulo è in preview, non ha un'ID di istanza. Ma un ID mi serve x forza per gli eventi. mode = _S("direct"); // Ajax non è supportato nell'anteprima, perchè non ho un id da referenziare secco per avere il contenuto in un secondo momento. } setID(controlID); if(mode == _S("ajax")) { // - Chiamo un "isDirect" a livello di ModuleViewer, che restituisce un "true" se son puntato diretto. // - Se si, leggo il parametro "mode", se è "direct" restituisco il contenuto del controllo secco via transmit-buffer if(getPage()->getRequest()->getUrlParam(_W("mode")) == _W("content")) mode = _S("content"); else mode = _S("delayed"); } if( (mode == _S("direct")) || (mode == _S("content")) ) { String url = root->getAttributeString(OS_MODULES_FEED_URL); bool showTitle = root->getAttributeBool(OS_MODULES_FEED_SHOWTITLE); bool showDescription = root->getAttributeBool(OS_MODULES_FEED_SHOWDESCRIPTION); bool showImage = root->getAttributeBool(OS_MODULES_FEED_SHOWIMAGE); int32 nItems = root->getAttributeInt32(OS_MODULES_FEED_NITEMS); String showItemDescription = root->getAttributeString(OS_MODULES_FEED_SHOWITEMDESCRIPTION); String templateModel = root->getAttributeString(OS_MODULES_FEED_TEMPLATEMODEL); String templateCustom = root->getAttributeString(OS_MODULES_FEED_TEMPLATECUSTOM); shared_ptr<XMLDocument> document(OS_NEW XMLDocument()); shared_ptr<XMLStylesheet> transformer(OS_NEW XMLStylesheet()); try { shared_ptr<boost::asio::io_service> service = getSession()->getService(); String output; String error; String userAgent = Engine::getDefaultHttpUserAgent(); document->parseUrl(url.to_ascii(), userAgent, service, Engine::instance()->createTCPSocket(service, true, true)); shared_ptr<XMLNode> rssRoot = document->getRoot(); if(rssRoot == nullptr) { // Error reading RSS Feed. error = _S("Feed reading error."); } else { // Aggiungo all'xml RSS le proprietà del modulo. rssRoot->setAttributeString(OS_MODULES_FEED_URL, url); rssRoot->setAttributeBool(OS_MODULES_FEED_SHOWTITLE, showTitle); rssRoot->setAttributeBool(OS_MODULES_FEED_SHOWDESCRIPTION, showDescription); rssRoot->setAttributeBool(OS_MODULES_FEED_SHOWIMAGE, showImage); rssRoot->setAttributeInt32(OS_MODULES_FEED_NITEMS, nItems); rssRoot->setAttributeString(OS_MODULES_FEED_SHOWITEMDESCRIPTION, showItemDescription); rssRoot->setAttributeString(OS_MODULES_FEED_TEMPLATEMODEL, templateModel); if(templateModel.empty()) { shared_ptr<XMLStylesheet> stylesheet(OS_NEW XMLStylesheet()); if(stylesheet->parseString(templateCustom)) { // Inizializza le funzioni del template getPage()->initStylesheet(stylesheet); if(stylesheet->applyToString(document, output)) { //getControls()->add(shared_ptr<HtmlLiteral>(OS_NEW HtmlLiteral(getPage()->parseBBCode(output, true, false, false, false)))); } else { // Transformazione fallita. error = _S("Transformation failed."); } } else { // Template custom invalido. error = _S("Invalid custom template."); } } else { shared_ptr<XMLStylesheet> stylesheet(OS_NEW XMLStylesheet()); // Inizializza le funzioni del template getPage()->initStylesheet(stylesheet); String path = utils::makeFilePath(utils::makeFolderPath(g_componentsPath, _S("feed")), _S("feed_viewer_") + templateModel + _S(".xsl")); // Carica l'xsl if(stylesheet->parseFile(path)) { if(stylesheet->applyToString(document, output)) { // Qui potrei aggiungere un literal diretto, non parserizzato bb... //getControls()->add(shared_ptr<HtmlLiteral>(OS_NEW HtmlLiteral(getPage()->parseBBCode(output, true, false, false, false)))); } else { // Transformazione fallita. error = _S("Transformation failed."); } } else { // Template non valido. error = _S("Invalid template."); } } if(output.empty() == true) { error = _S("Unknown error."); } } if(error.empty() == false) { divData->setCss(_S("os_plugins_components_feed_error_reading")); divData->getControls()->add(shared_ptr<HtmlText>(OS_NEW HtmlText(error))); } else { divData->setCss(_S("os_plugins_components_feed_ok")); output = output.trim(); //output = _S("[nobr]") + output + _S("[/nobr]"); // Debugging //output = _S("[code]") + output + _S("[/code]") + output; divData->getControls()->add(shared_ptr<HtmlLiteral>(OS_NEW HtmlLiteral(getPage()->parseOml(output, true, false, false, omlRenderModeOsiris, getInstance().getString())))); } } catch(std::exception &e) { OS_LOG_ERROR(e.what()); } } if(mode == _S("direct")) { getControls()->add(divData); } else if(mode == _S("delayed")) { String urlAjaxContent = getPage()->getPortal()->getViewObjectLink(getInstance()) + _S("&mode=content"); divData->getControls()->add(shared_ptr<HtmlLiteral>(OS_NEW HtmlLiteral(_S("<div data-os-wait=\"center\" data-os-url=\"") + urlAjaxContent + _S("\"></div>")))); getControls()->add(divData); } else if(mode == _S("content")) { // trasmitbuffer solo di divData. HtmlWriter writer; divData->render(getPage(), writer); getPage()->getSession()->transmitHtml(writer.getHtml().to_utf8(), httpStatusOK); } }
void ConsoleMsg(const wchar* msg) { CEngine::cConsole()->AddMsg(MSG_INFO, _W("%s"), msg); }
void cButtonHandler::Update(float afTimeStep) { static bool bLockState = true; /////////////////////////////////// // GLOBAL Key Strokes /////////////////////////////////// if(mpInput->BecameTriggerd("QuitGame")) { mpInit->mpGame->Exit(); } if(mpInput->BecameTriggerd("Screenshot")) { int lCount = 1; tString sFileName = "screenshot000.bmp"; while(FileExists(cString::To16Char(sFileName))) { sFileName = "screenshot"; if(lCount < 10)sFileName+= "00"; else if(lCount < 100)sFileName+= "0"; sFileName += cString::ToString(lCount); sFileName += ".bmp"; ++lCount; } mpInit->mpGame->GetGraphics()->GetLowLevel()->SaveScreenToBMP(sFileName); } if(mpInput->BecameTriggerd("LockInput")) { #ifndef WIN32 bLockState = !bLockState; mpInit->mpGame->GetInput()->GetLowLevel()->LockInput(bLockState); #endif } /////////////////////////////////// // DEMO END TEXT /////////////////////////////////// if(mState == eButtonHandlerState_DemoEndText) { if( mpInput->BecameTriggerd("Escape")) mpInit->mpDemoEndText->OnButtonDown(); if(mpInput->BecameTriggerd("LeftClick")) mpInit->mpDemoEndText->OnMouseDown(eMButton_Left); if(mpInput->BecameTriggerd("RightClick")) mpInit->mpDemoEndText->OnMouseDown(eMButton_Right); } /////////////////////////////////// // CREDITS STATE /////////////////////////////////// else if(mState == eButtonHandlerState_Credits) { if( mpInput->BecameTriggerd("Escape")) mpInit->mpCredits->OnButtonDown(); if(mpInput->BecameTriggerd("LeftClick")) mpInit->mpCredits->OnMouseDown(eMButton_Left); if(mpInput->BecameTriggerd("RightClick")) mpInit->mpCredits->OnMouseDown(eMButton_Right); } /////////////////////////////////// // PRE MENU STATE /////////////////////////////////// else if(mState == eButtonHandlerState_PreMenu) { if( mpInput->BecameTriggerd("Escape")) mpInit->mpPreMenu->OnButtonDown(); if(mpInput->BecameTriggerd("LeftClick")) mpInit->mpPreMenu->OnMouseDown(eMButton_Left); if(mpInput->BecameTriggerd("RightClick")) mpInit->mpPreMenu->OnMouseDown(eMButton_Right); } /////////////////////////////////// // MAP LOAD TEXT STATE /////////////////////////////////// else if(mState == eButtonHandlerState_MapLoadText) { if( mpInput->BecameTriggerd("Escape") || mpInput->BecameTriggerd("RightClick") || mpInput->BecameTriggerd("LeftClick")) { mpInit->mpMapLoadText->SetActive(false); } } /////////////////////////////////// // MAIN MENU BUTTON STATE /////////////////////////////////// else if(mState == eButtonHandlerState_MainMenu) { if(mpInput->BecameTriggerd("Escape")) { mpInit->mpMainMenu->Exit(); } if( mpInput->BecameTriggerd("RightClick") || (mpInit->mbHasHaptics && mpInput->BecameTriggerd("MouseClickRight")) ) { mpInit->mpMainMenu->OnMouseDown(eMButton_Right); mpInput->BecameTriggerd("Examine"); } if(mpInput->WasTriggerd("RightClick")) { mpInit->mpMainMenu->OnMouseUp(eMButton_Right); } if(mpInput->DoubleTriggerd("RightClick",0.15f)) { mpInit->mpMainMenu->OnMouseDoubleClick(eMButton_Right); } if( mpInput->BecameTriggerd("LeftClick") || (mpInit->mbHasHaptics && mpInput->BecameTriggerd("MouseClick")) ) { mpInit->mpMainMenu->OnMouseDown(eMButton_Left); mpInput->BecameTriggerd("Interact"); } if(mpInput->WasTriggerd("LeftClick")) { mpInit->mpMainMenu->OnMouseUp(eMButton_Left); } if(mpInput->DoubleTriggerd("LeftClick",0.15f)) { mpInit->mpMainMenu->OnMouseDoubleClick(eMButton_Left); } if(mpInit->mbHasHaptics) { mpInit->mpMainMenu->AddMousePos(mpLowLevelHaptic->GetRelativeVirtualMousePos() * mfMouseSensitivity); cVector2f vRel = mpInput->GetMouse()->GetRelPosition(); mpInit->mpMainMenu->AddMousePos(vRel * mfMouseSensitivity); } else { /// Mouse Movement cVector2f vRel = mpInput->GetMouse()->GetRelPosition(); mpInit->mpMainMenu->AddMousePos(vRel * mfMouseSensitivity); } } /////////////////////////////////// // INTRO BUTTON STATE /////////////////////////////////// else if(mState == eButtonHandlerState_Intro) { if(mpInput->BecameTriggerd("Escape")) { mpInit->mpIntroStory->Exit(); } } /////////////////////////////////// // GAME BUTTON STATE /////////////////////////////////// else if(mState == eButtonHandlerState_Game) { /////////////////////////////////////// // Global //////////////////// /*if(mpInput->BecameTriggerd("ResetGame")) { mpInit->ResetGame(true); mpInit->mpMapHandler->Load( mpInit->msStartMap,mpInit->msStartLink); }*/ if(mpInit->mbAllowQuickSave) { if(mpInput->BecameTriggerd("SaveGame")) { mpInit->mpSaveHandler->AutoSave(_W("auto"),5); } if(mpInput->BecameTriggerd("LoadGame")) { mpInit->mpSaveHandler->AutoLoad(_W("auto")); } } if(mpInput->BecameTriggerd("PrintLog")) { Log("-------------- START RENDERING LOG ------------------------\n"); mpInit->mpGame->GetGraphics()->GetRenderer3D()->SetDebugFlags(eRendererDebugFlag_LogRendering); } //Check if no jump is pressed always. bool bPlayerStateIsActive = false; /////////////////////////////////////// // Death menu //////////////////// if(mpInit->mpDeathMenu->IsActive()) { if(mpInput->BecameTriggerd("Escape")) { mpInit->mpGame->GetUpdater()->Reset(); mpInit->mpMainMenu->SetActive(true); } if(mpInput->BecameTriggerd("RightClick")) { mpInit->mpDeathMenu->OnMouseDown(eMButton_Right); mpInput->BecameTriggerd("Examine"); } if(mpInput->BecameTriggerd("LeftClick")) { mpInit->mpDeathMenu->OnMouseDown(eMButton_Left); mpInput->BecameTriggerd("Interact"); } if(mpInput->WasTriggerd("LeftClick")) { mpInit->mpDeathMenu->OnMouseUp(eMButton_Left); } if(mpInit->mbHasHaptics) { mpInit->mpDeathMenu->AddMousePos(mpLowLevelHaptic->GetRelativeVirtualMousePos() * mfMouseSensitivity); } else { /// Mouse Movement cVector2f vRel = mpInput->GetMouse()->GetRelPosition(); mpInit->mpDeathMenu->AddMousePos(vRel * mfMouseSensitivity); } } /////////////////////////////////////// // Death //////////////////// else if(mpPlayer->IsDead()) { if(mpInput->BecameTriggerd("Escape")) { mpInit->mpMainMenu->SetActive(true); } } /////////////////////////////////////// // Numerical panel //////////////////// else if(mpInit->mpNumericalPanel->IsActive()) { if(mpInput->BecameTriggerd("Inventory") || mpInput->BecameTriggerd("Escape")) { mpInit->mpNumericalPanel->OnExit(); } if(mpInput->BecameTriggerd("RightClick")) { mpInit->mpNumericalPanel->OnExit(); } if(mpInput->BecameTriggerd("LeftClick")) { mpInit->mpNumericalPanel->OnMouseDown(eMButton_Left); mpInput->BecameTriggerd("Interact"); } if(mpInput->WasTriggerd("LeftClick")) { mpInit->mpNumericalPanel->OnMouseUp(eMButton_Left); } if(mpInit->mbHasHaptics) { mpInit->mpNumericalPanel->AddMousePos(mpLowLevelHaptic->GetRelativeVirtualMousePos() * mfMouseSensitivity); } else { /// Mouse Movement cVector2f vRel = mpInput->GetMouse()->GetRelPosition(); mpInit->mpNumericalPanel->AddMousePos(vRel * mfMouseSensitivity); } } /////////////////////////////////////// // Notebook //////////////////// else if(mpInit->mpNotebook->IsActive()) { if(mpInput->BecameTriggerd("Inventory") || mpInput->BecameTriggerd("Escape")) { mpInit->mpNotebook->OnExit(); } if(mpInput->BecameTriggerd("LeftClick")) { mpInit->mpNotebook->OnMouseDown(eMButton_Left); mpInput->BecameTriggerd("Interact"); } if(mpInput->BecameTriggerd("NoteBook")) { mpInit->mpNotebook->OnExit(); } if(mpInput->BecameTriggerd("PersonalNotes")) { cStateMachine *pStateMachine = mpInit->mpNotebook->GetStateMachine(); if(pStateMachine->CurrentState()->GetId() == eNotebookState_TaskList) { pStateMachine->ChangeState(eNotebookState_Front); mpInit->mpNotebook->OnExit(); } else { pStateMachine->ChangeState(eNotebookState_TaskList); } } if(mpInit->mbHasHaptics) { mpInit->mpNotebook->AddMousePos(mpLowLevelHaptic->GetRelativeVirtualMousePos() * mfMouseSensitivity); } else { /// Mouse Movement cVector2f vRel = mpInput->GetMouse()->GetRelPosition(); mpInit->mpNotebook->AddMousePos(vRel * mfMouseSensitivity); } } /////////////////////////////////////// // Inventory //////////////////// else if(mpInit->mpInventory->IsActive()) { //////////////////////////// //Normal Input if(mpInput->BecameTriggerd("Inventory") || mpInput->BecameTriggerd("Escape")) { mpInit->mpInventory->OnInventoryDown(); } if(mpInput->BecameTriggerd("LeftClick")) { mpInit->mpInventory->OnMouseDown(eMButton_Left); mpInput->BecameTriggerd("Interact"); } if(mpInput->DoubleTriggerd("LeftClick",0.2f)) { mpInit->mpInventory->OnDoubleClick(eMButton_Left); } if(mpInput->WasTriggerd("LeftClick")) { mpInit->mpInventory->OnMouseUp(eMButton_Left); } if(mpInput->BecameTriggerd("RightClick")) { mpInit->mpInventory->OnMouseDown(eMButton_Right); mpInput->BecameTriggerd("Examine"); } if(mpInput->WasTriggerd("RightClick")) { mpInit->mpInventory->OnMouseUp(eMButton_Right); } ////////////////////////////// //Short cut keys if(mpInput->BecameTriggerd("One")) mpInit->mpInventory->OnShortcutDown(0); if(mpInput->BecameTriggerd("Two")) mpInit->mpInventory->OnShortcutDown(1); if(mpInput->BecameTriggerd("Three")) mpInit->mpInventory->OnShortcutDown(2); if(mpInput->BecameTriggerd("Four")) mpInit->mpInventory->OnShortcutDown(3); if(mpInput->BecameTriggerd("Five")) mpInit->mpInventory->OnShortcutDown(4); if(mpInput->BecameTriggerd("Six")) mpInit->mpInventory->OnShortcutDown(5); if(mpInput->BecameTriggerd("Seven")) mpInit->mpInventory->OnShortcutDown(6); if(mpInput->BecameTriggerd("Eight")) mpInit->mpInventory->OnShortcutDown(7); if(mpInput->BecameTriggerd("Nine")) mpInit->mpInventory->OnShortcutDown(8); if(mpInit->mbHasHaptics) { cVector2f vRel = mpLowLevelHaptic->GetRelativeVirtualMousePos(); mpInit->mpInventory->AddMousePos(vRel * mfMouseSensitivity); } else { /// Mouse Movement cVector2f vRel = mpInput->GetMouse()->GetRelPosition(); mpInit->mpInventory->AddMousePos(vRel * mfMouseSensitivity); } } else { bPlayerStateIsActive = true; if(mpInput->BecameTriggerd("Escape")) { mpInit->mpMainMenu->SetActive(true); } if(mpInput->BecameTriggerd("Hit")) { mpInit->mpPlayer->Damage(20,ePlayerDamageType_BloodSplash); } /*if(mpInput->BecameTriggerd("Log")) { mpInit->mpGame->GetPhysics()->SetDebugLog(!mpInit->mpGame->GetPhysics()->GetDebugLog()); }*/ if(mpInput->BecameTriggerd("Taunt")) { for(int i=0;i<10; ++i) mpInit->mpGame->GetSound()->GetSoundHandler()->PlayGui("gui_notebook_add_note1", false,0.01f); /*cVector3f vPos = mpInit->mpPlayer->GetCharacterBody()->GetPosition(); cSoundEntity *pSound = mpInit->mpGame->GetScene()->GetWorld3D()->CreateSoundEntity("Taunt","interact_homer",true); if(pSound) { pSound->SetPosition(vPos); }*/ } if(mpPlayer->IsActive() || mpPlayer->GetState() == ePlayerState_Message) { if(mpPlayer->IsActive()) { if(mpInput->BecameTriggerd("Inventory")) { mpPlayer->StartInventory(); } if(mpInput->BecameTriggerd("NoteBook")) { mpInit->mpNotebook->SetActive(true); } if(mpInput->BecameTriggerd("PersonalNotes")) { mpInit->mpNotebook->SetActive(true); mpInit->mpNotebook->GetStateMachine()->ChangeState(eNotebookState_TaskList); } if(mpInput->BecameTriggerd("Flashlight")) { mpPlayer->StartFlashLightButton(); } if(mpInput->BecameTriggerd("GlowStick")) { mpPlayer->StartGlowStickButton(); } /////////////////////////////////////// // Player Movement //////////////////// if(mpInput->IsTriggerd("Forward")) { mpPlayer->MoveForwards(1,afTimeStep); } else if(mpInput->IsTriggerd("Backward")) { mpPlayer->MoveForwards(-1,afTimeStep); } else { mpPlayer->MoveForwards(0,afTimeStep); } if(mpInput->IsTriggerd("Left")) { mpPlayer->MoveSideways(-1,afTimeStep); } else if(mpInput->IsTriggerd("Right")) { mpPlayer->MoveSideways(1,afTimeStep); } else { mpPlayer->MoveSideways(0,afTimeStep); } if(mpInput->IsTriggerd("LeanLeft")) { mpPlayer->Lean(-1,afTimeStep); } else if(mpInput->IsTriggerd("LeanRight")) { mpPlayer->Lean(1,afTimeStep); } if(mpInput->BecameTriggerd("Jump")) { mpPlayer->Jump(); } if(mpInput->IsTriggerd("Jump")) { mpPlayer->SetJumpButtonDown(true); } if(mpInput->BecameTriggerd("Run")) { mpPlayer->StartRun(); } if(mpInput->WasTriggerd("Run")) { mpPlayer->StopRun(); } if(mpInput->BecameTriggerd("Crouch")) { mpPlayer->StartCrouch(); } if(GetToggleCrouch()) { if(mpInput->WasTriggerd("Crouch")) mpPlayer->StopCrouch(); } else { if(mpInput->IsTriggerd("Crouch")==false) mpPlayer->StopCrouch(); } if(mpInput->BecameTriggerd("InteractMode")) { if(mpInit->mbHasHaptics==false) { mpPlayer->StartInteractMode(); } else { //DO nothing for the time being. } } //Get the mouse pos and convert it to 0 - 1 if(mpInit->mbHasHaptics==false) { cVector2f vRel = mpInput->GetMouse()->GetRelPosition(); vRel /= mpLowLevelGraphics->GetVirtualSize(); if (mpInit->mbRiftSupport==true) { // Use HMD for yaw, pitch, roll TODO make roll controllable for camera - no lean? mpPlayer->AddYaw(-mpHMD->getYawDelta()); mpPlayer->AddPitch(-mpHMD->getPitchDelta()); mpPlayer->AddLean(-mpHMD->getRollDelta()); // Update mouse if interact mode if ( mpPlayer->GetState() == ePlayerState_InteractMode) { mpPlayer->AddYaw(vRel.x * mfMouseSensitivity); mpPlayer->AddPitch(vRel.y * mfMouseSensitivity); } } mpPlayer->AddYaw(vRel.x * mfMouseSensitivity); mpPlayer->AddPitch(vRel.y * mfMouseSensitivity); } } /////////////////////////////////////// // Player Interaction ///////////////// if( mpInput->BecameTriggerd("Interact")) { mpPlayer->StartInteract(); mpInput->BecameTriggerd("LeftClick"); } if( mpInput->WasTriggerd("Interact")) { mpPlayer->StopInteract(); } if( mpInput->BecameTriggerd("Examine")) { mpPlayer->StartExamine(); } if(mpInput->WasTriggerd("Examine")) { mpPlayer->StopExamine(); } if(mpInput->BecameTriggerd("Holster")) { mpPlayer->StartHolster(); } if(mpPlayer->IsActive()) { if(mpInput->BecameTriggerd("One")) mpPlayer->StartInventoryShortCut(0); if(mpInput->BecameTriggerd("Two")) mpPlayer->StartInventoryShortCut(1); if(mpInput->BecameTriggerd("Three")) mpPlayer->StartInventoryShortCut(2); if(mpInput->BecameTriggerd("Four")) mpPlayer->StartInventoryShortCut(3); if(mpInput->BecameTriggerd("Five")) mpPlayer->StartInventoryShortCut(4); if(mpInput->BecameTriggerd("Six")) mpPlayer->StartInventoryShortCut(5); if(mpInput->BecameTriggerd("Seven")) mpPlayer->StartInventoryShortCut(6); if(mpInput->BecameTriggerd("Eight")) mpPlayer->StartInventoryShortCut(7); if(mpInput->BecameTriggerd("Nine")) mpPlayer->StartInventoryShortCut(8); } } } if(mpInput->IsTriggerd("Jump")==false || bPlayerStateIsActive==false) { mpPlayer->SetJumpButtonDown(false); } } }
namespace P3D { Model *model; // debug REGISTER_MODULE_CLASS(CEngine, _W("engine"), _W("internal")); CEngine* CEngine::s_pEngine=NULL; bool CEngine::s_bInit=false; // external IRenderer *CEngine::s_pRenderer=NULL; ISoundEngine *CEngine::s_pSound=NULL; IPhysEngine *CEngine::s_pPhys=NULL; IFileSystem *CEngine::s_pFS=NULL; IGUI *CEngine::s_pGUI=NULL; //------------------------------------------ CEngine::CEngine(){ assert(s_pEngine==NULL); s_pEngine=this; m_fDeltaTime=0.001f; m_nFrameNumber=0; m_bModulesLoaded=false; m_bShutdownRequested=false; } //------------------------------------------ CEngine::~CEngine(){ cConfig()->Save(m_szSettings); delete[] m_szSettings; UNLOAD_SUBCLASS(Filesystem); UNLOAD_SUBCLASS(InputManager); UNLOAD_SUBCLASS(SceneManager); UNLOAD_SUBCLASS(Config); UNLOAD_SUBCLASS(MeshLoader); UNLOAD_SUBCLASS(ObjectManager); UNLOAD_SUBCLASS(ScriptEngine); UNLOAD_SUBCLASS(InternalWindow); UNLOAD_SUBCLASS(InternalInput); UNLOAD_SUBCLASS(Console); // should be last } //------------------------------------------ int CEngine::GetBuildNum() { // make build number based on number of days since const char* pszDate = __DATE__; // will be in format of Apr 24 2006 const char *pszMonths[12] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; BYTE nMonthDays[12] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; // number of days from 1.1.2008 to 1.1.ThisYear UINT nBuild = (atoi(&pszDate[7])-2008)*365; for(UINT i=0;i<12;i++)// go through all the months { if(!strncmp(pszDate, pszMonths[i], 3)) break; // Linux: byl tu strnicmp nBuild+=nMonthDays[i]; } nBuild+=atoi(&pszDate[4]); // add number of days in month today in this month nBuild-=60; // subtract days from 1.1.2008 to 1.3.2008 = 60 return nBuild; } //------------------------------------------ const wchar* CEngine::GetBuildString() { static wchar bs[256]; wchar platform[16]; #if defined(_WIN32) # if defined(_WIN64) wstrcpy(platform, _W("Win64") ); # else wstrcpy(platform, _W("Win32") ); # endif #elif LINUX wstrcpy(platform, _W("Linux") ); #elif __MACOSX__ wstrcpy(platform, _W("Mac") ); #else wstrcpy(platform, _W("Other platform") ); #endif wsprintf( bs, 255, _W("%s (build %d, %s) <%s>"), _W(P3DNAME), GetBuildNum(), _W(__DATE__), platform ); return bs; } void ConsoleMsg(const wchar* msg) { CEngine::cConsole()->AddMsg(MSG_INFO, _W("%s"), msg); } // Engine.Modules static SVar svRenderer(_W("Renderer"), _W("Engine.Modules"), _W("DX9"), _W("Renderer module implementation to load.")); static SVar svSound(_W("Sound"), _W("Engine.Modules"), _W("OAL"), _W("Sound engine module implementation to load.")); static SVar svPhysics(_W("Physics"), _W("Engine.Modules"), _W("PhysX"), _W("Physics engine module implementation to load.")); static SVar svFileSystem(_W("FileSystem"), _W("Engine.Modules"), _W("StdIO"), _W("Filesystem module implementation to load.")); static SVar svGUI(_W("GUI"), _W("Engine.Modules"), _W("Internal"), _W("GUI module implementation to load.")); // Engine.Client static SVar svResolutionX(_W("ResolutionX"), _W("Engine.Client"), 800, _W("Startup screen/window width.")); static SVar svResolutionY(_W("ResolutionY"), _W("Engine.Client"), 600, _W("Startup screen/window height.")); static SVar svFullscreen(_W("Fullscreen"), _W("Engine.Client"), false, _W("Start fullscreen?")); // TODO: FINAL: change to true? double milisec() /* From 1970-01-01T00:00:00 */ { SYSTEMTIME st; /* unsigned wMilliseconds; */ union _t { FILETIME ft; __int64 tlong; } t; GetSystemTime(&st); SystemTimeToFileTime(&st,&t.ft); return (double)((t.tlong-116444736000000000i64)/10000); } //------------------------------------------ bool CEngine::Initialize(const wchar* settings/*="game.ini"*/, bool customWindow/*=false*/, sDisplayProperties *dp/*=NULL*/){ assertd(s_bInit==false, "DOUBLE ENGINE INITIALIZATION!"); s_bInit = true; //predict :-P // initialize random generator srand( (unsigned int)milisec() ); cInternalWindow()->BeginSplash(); // memory leaks detection #if defined(_DEBUG) && defined(_MSC_VER) && _MSC_VER >= 800 _CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF ); //_CrtSetBreakAlloc(23296); #endif // --------------------------------------------------- // QUEUE TESTS CON(MSG_INFO, _W("------- Command Queue Test -------")); CCommandQueue q; DWORD tim; for (int t=0; t<10; t++) { tim = GetTickCount(); // FILL IN QUEUE for (int i=0; i<20000; i++) { sE2RCanvasDesc *cd; q.Enqueue(NULL, CQI_ENGINE2RENDERER_CANVAS_CREATE, (void*&)cd, sizeof(sE2RCanvasDesc)); cd->handle = 0; } CON(MSG_INFO, _W("Iteration #%d: Enqueue %d ms"), t, GetTickCount()-tim ); // DEQUEUE unsigned int cqi; const void* optr; IQueueCommandReceiver *recv; tim = GetTickCount(); while (q.Dequeue(cqi, optr, recv)) { switch(cqi) { case CQI_ENGINE2RENDERER_CANVAS_CREATE: { sE2RCanvasDesc *cd = (sE2RCanvasDesc *)optr; } break; } } CON(MSG_INFO, _W("Iteration #%d: Dequeue %d ms"), t, GetTickCount()-tim ); } CON(MSG_INFO, _W("----------------------------------")); // --------------------------------------------------- // --- WRITE INFO ABOUT LIBRARIES AND MODULES I_DebugPrint( ConsoleMsg ); CON(MSG_INFO, _W("= %s %s build %d initialization ="), _W(P3DNAME), sizeof(void*)==8?_W("x64"):_W("x86"), GetBuildNum()); if (sizeof(wchar)>1) CON(MSG_INFO, _W("Unicode support \x263A")); else CON(MSG_INFO, _W("Multibyte character set")); // --- LOAD SETTINGS m_szSettings = new wchar[wstrlen(settings)+1]; wstrcpy(m_szSettings, settings); cConfig()->Load(m_szSettings); //cConfig()->Save(m_szSettings); // --- INITIALIZE SCRIPT SYSTEM CON(MSG_INFO, _W("Script system initialization")); cScriptEngine()->Initialize(); // --- LOAD KEY BINDINGS cInputManager()->Assign(_W("GUI_CURSOR"), WE_MOUSE_MOTION, 0); cInputManager()->Assign(_W("GUI_SELECT"), WE_MOUSE_DOWN, 0); cInputManager()->Save(_W("keys.ini")); // TODO: FIXME: What about load? :D // --- CREATE MAIN WINDOW Vec2i mainWindowSize(800,600); bool initFullscreen = false; if (customWindow) { // use primary screen resolution for frame buffer // TODO: multiplatform #ifdef _WIN32 mainWindowSize.x = GetSystemMetrics(SM_CXSCREEN); mainWindowSize.y = GetSystemMetrics(SM_CYSCREEN); #endif } else { if (dp) { // use user-defined resolution initFullscreen = dp->Fullscreen; mainWindowSize.x = dp->HorRes; mainWindowSize.y = dp->VertRes; } else { // use settings initFullscreen = svFullscreen.GetBool(); mainWindowSize.x = svResolutionX.GetInt(); mainWindowSize.y = svResolutionY.GetInt(); } } cInternalWindow()->Create(mainWindowSize); //Init the internal input system cInternalInput()->Init( cInternalWindow()->GetHandle() ); //Init the Filesystem cFilesystem()->Init(); // --- LOAD SELECTED MODULES s_pRenderer = (IRenderer*)I_GetModule(_W("renderer"), svRenderer.GetString()); if (!s_pRenderer) CON(MSG_ERR_FATAL, _W("Cannot load renderer module. It is a core module, cannot continue!")); s_pSound = (ISoundEngine*)I_GetModule(_W("sound"), svSound.GetString()); if (!s_pSound) CON(MSG_ERR_FATAL, _W("Cannot load sound module. It is a core module, cannot continue!")); s_pPhys = (IPhysEngine*)I_GetModule(_W("physics"), svPhysics.GetString()); if (!s_pPhys) CON(MSG_ERR_FATAL, _W("Cannot load phys module. It is a core module, cannot continue!")); s_pFS = (IFileSystem*)I_GetModule(_W("filesystem"), svFileSystem.GetString()); if (!s_pFS) CON(MSG_ERR_FATAL, _W("Cannot load filesystem module. It is a core module, cannot continue!")); s_pGUI = (IGUI*)I_GetModule(_W("gui"), svGUI.GetString()); if (!s_pGUI) CON(MSG_ERR_FATAL, _W("Cannot load GUI module. It is a core module, cannot continue!")); m_bModulesLoaded=true; // ==== INITIALIZE MODULES ==== s_pRenderer->Initialize(this, &m_queueRenderer); bool ret = s_pRenderer->iGraphicsDevice()->Initialize(mainWindowSize.x, mainWindowSize.y, initFullscreen, cInternalWindow()->GetHandle()); if (!ret) { CON(MSG_ERR_FATAL, _W("Failed to initialize graphics device!")); } // ===== SERIALIZATION DEBUG AND TEST ======= Scene scene; //scene.Save(s_pFS, _W("scenes/test.robject"), iConsole()); //CModel model; /*model = (Model*)cObjectManager()->CreateObject( _W("Model") ); MeshData md; MeshSubset ms; // Material m; // ms.Material = m; ms.NumTriangles = 1; ms.StartIndex = 0; //ms.StartVertex = 0; md.Subsets.AddEx(ms); md.Indices.AddEx(0); md.Indices.AddEx(1); md.Indices.AddEx(2); md.NumIndices = 3; MeshVertexData mvd; mvd.Usage = _W("P3DVU_POSITION"); mvd.DataSize = 3; mvd.Float3.AddEx(Vec3Param(0.0f, 0.0f, 0.0f)); mvd.Float3.AddEx(Vec3Param(0.0f, 1.0f, 0.0f)); mvd.Float3.AddEx(Vec3Param(1.0f, 1.0f , 0.0f)); md.DataStreams.AddEx(mvd); md.NumVerts = 3; model->LODs.AddEx(md); model->Save(s_pFS, _W("triangle.robject"), iConsole()); model->PreCache();*/ // =========================================== bool initOK=true; initOK &= s_pSound->Initialize(this); initOK &= s_pPhys->Initialize(this); initOK &= s_pFS->Initialize(this); initOK &= s_pGUI->Initialize(this); if (!initOK) CON(MSG_ERR_FATAL, _W("Failed to initialize some core module(s)! Cannot continue. For more details see console.htm.")); cSceneManager()->Create(); cConsole()->InitializeGUI(); // at this time, coz it uses GUI module and it must be initialized ;) // FIXME: register engine to script, temporary here /*using namespace luabind; lua_State* L = cScriptEngine()->GetLVM(); module(L) [ class_<CEngine>("Engine") .scope [ def("GetBuildNum", &CEngine::GetBuildNum ) ] ];*/ // load bootstrap script cScriptEngine()->LoadScript(_W("scripts/bootstrap.rscript")); // DEBUG TESTING OF QUEUE TO RENDERER sE2RCanvasDesc* canvas; EnqueueMessage( MC_RENDERER, this, CQI_ENGINE2RENDERER_CANVAS_CREATE, (void*&)canvas, sizeof(sE2RCanvasDesc) ); canvas->handle = cInternalWindow()->GetHandle(); canvas->size = Vec2i(800,600); canvas->windowed = !initFullscreen; //Sleep(10000); cInternalWindow()->EndSplash(); cInternalWindow()->SetVisible(true); //Filesystem test /*UINT oSize; void *lData=0; if(cFilesystem()->Load(_W("scripts.bootstrap"), &lData, oSize)==P3D_FILERESULT_OK) cFilesystem()->FreeLoadedData(lData); const char* testStr = "this is a test string"; cFilesystem()->Save(_W("scripts.fstest"), testStr, sizeof(char)*strlen(testStr));*/ return true; } //------------------------------------------ bool CEngine::NextFrame(){ // -------- compute and filter frame time ------------------------------------------------------------ m_timer.Loop(); // move all time buffer values to the right and at set new value at the beginning for(int i=MAX_FILTER_VALUES-1; i>0; i--) m_fFilterArray[i]=m_fFilterArray[i-1]; m_fFilterArray[0] = m_timer.GetTime_s(); // filter values only when buffer is filled if (m_nFrameNumber<MAX_FILTER_VALUES) { m_fDeltaTime = m_fFilterArray[0]; // immediate, non filtered m_nFPS = (int)(1.0f/m_fDeltaTime); m_nFrameNumber++; } else { m_nFPS = (int)(1.0f/m_fDeltaTime); // filter values based on FPS int numVal = m_nFPS; float fSum=0; if (numVal<2) numVal=2; else if(numVal>MAX_FILTER_VALUES-1) numVal = MAX_FILTER_VALUES-1; for (int i=0; i<numVal; i++) fSum+=m_fFilterArray[i]/(i+1); m_fDeltaTime = fSum/log((float)numVal*1.75f); } // ----------------------------------------------------------------------------------------- // ---- update script engine cScriptEngine()->Tick(); // ---- begin frame ------------------------------------------------------------------------ // {** this is main engine frame time... here should be all script work done, messages added to queues **} // -- Swap all command queues m_queueRenderer.Swap(); // -- Execute rendering in separate thread; TODO: separate thread mRenderer()->NextFrame(); // ...but in separate thread // todo: execute other threads // -- Wait for all threads (also maybe proccess queues from finished threads?) // -- Process renderer back command queue unsigned int cqi=0; const void* ptr=NULL; IQueueCommandReceiver* recv=NULL; while( m_queueRenderer.EngineQueue()->Dequeue(cqi, ptr, recv) ) { if ( recv ) recv->OnMessageReceived( cqi, ptr ); } // old code commented out, just for reference, remove after implemented in a new way /* unsigned int numEvents=0; sWEvent* we=NULL; if (wndTarget) { sViewport vp; vp.x = vp.y = 0; vp.width = wndTarget->GetSize().x; vp.height = wndTarget->GetSize().y; //s_pRenderer->iGraphicsDevice()->SetViewport(vp); // get events from custom window we = wndTarget->GetEvents(numEvents); } else { // get events from internal window we = s_pRenderer->iGraphicsWindow()->GetEvents(numEvents); } // send events to InputManager cInputManager()->ProcessNewEvents(we, numEvents); // process all returned events for (unsigned int i=0;i<numEvents;i++) { if (we[i].type==WE_RESIZE) { break; } else if (we[i].type==WE_KEY_DOWN) {*/ /*if (we[i].button==KEY_BACKQUOTE) { bool bVisible = cConsole()->ToggleVisible(); if (wndTarget) wndTarget->SetMenuMode(bVisible); else s_pRenderer->iGraphicsWindow()->SetMenuMode(bVisible); }*/ /*} else if (we[i].type==WE_QUIT) { ret = false; // inform about shutdown request CON(MSG_INFO, _W("Shutdown request.")); } }*/ //TODO: Run this in a separate thread cInternalWindow()->Update(); cInternalInput()->Update(); tArray<sInputEvent> ievents; cInternalInput()->SwapEvents(ievents); cInputManager()->ProcessNewEvents(ievents); //return false; // DEBUG:!! Temporary do only one frame return !m_bShutdownRequested; } //------------------------------------------ bool CEngine::SendScriptCommands(tArray<Str> &commands) { bool allOk=true; for(unsigned int i=0; i<commands.Size(); i++) { if( !cScriptEngine()->LoadScriptString( _W2A(commands[i].Get()) ) ) allOk = false; } return allOk; } //------------------------------------------ void CEngine::EnqueueMessage(eModuleClass toModule, IQueueCommandReceiver* receiver, unsigned int commandQueueIdentifier, void* &inOutPointer, unsigned int memSizeInBytes) { switch(toModule) { case MC_RENDERER: m_queueRenderer.EngineQueue()->Enqueue(receiver, commandQueueIdentifier, inOutPointer, memSizeInBytes); break; } } //------------------------------------------ void CEngine::OnMessageReceived(unsigned int commandQueueIdentifier, const void* &outPointer) { int debug=0; } //------------------------------------------ //void CEngine::EndScene(){ //debug /*Matrix mat; mat.SetIdentityMatrix(); GeometryChunk gc; gc.Data = &model->LODs[0]; gc.Subset = &model->LODs[0].Subsets[0]; gc.WorldMatrix = &mat; tArray<GeometryChunk> chunks; chunks.AddEx(gc); s_pRenderer->iGraphicsRenderer()->SendChunks(chunks);*/ /*s_pGUI->Update(m_fDeltaTime); s_pGUI->Render(m_fDeltaTime);*/ // draw text on screen //cConsole()->Draw(); //mRenderer()->iTextRenderer()->Render(); //s_pRenderer->iGraphicsDevice()->EndScene(); //} };
namespace P3D { REGISTER_MODULE_CLASS(CGUI, _W("gui"), _W("internal")); // - external modules IEngine* CGUI::s_pEngine=NULL; IRenderer* CGUI::s_pRenderer=NULL; //----------------------------------------- bool CGUI::Initialize(void* pEngineV) { // memory leaks detection #if defined(_DEBUG) && defined(_MSC_VER) && _MSC_VER >= 800 _CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF ); //_CrtSetBreakAlloc(111); #endif s_pEngine = (IEngine*) pEngineV; s_pRenderer = mEngine()->mRenderer(); INIT_SUBCLASS(GUIScheme); return true; } //----------------------------------------- CGUI::~CGUI() { // release all window guis for (unsigned int i=0; i<m_windows.Size(); i++) SAFE_DELETE(m_windows[i]); UNLOAD_SUBCLASS(GUIScheme); } //----------------------------------------------- IGUIWindow* CGUI::CreateWindow(const wchar* caption, Vec2i pos, Vec2i size, bool showInTaskBar) { CGUIWindow *win = new CGUIWindow(caption, pos, size, showInTaskBar); m_windows.AddEx(win); return win; } //----------------------------------------------- void CGUI::Update(float deltaTime) { Vec2i mousePos; mEngine()->iInputManager()->GetMousePos(mousePos); // get new mouse pos // update all windows for (unsigned int i=0; i<m_windows.Size(); i++) { m_windows[i]->Update(deltaTime); } } //------------------------------------------------ void CGUI::Render(float deltaTime) { // draw all windows for (unsigned int i=0; i<m_windows.Size(); i++) if (m_windows[i]->IsVisible()) m_windows[i]->Render(deltaTime); // draw mouse cursor // mRenderer()->iPrimitiveRenderer()->AddLine(g_mousePos, g_mousePos+10, ColorRGBA(0, 1, 1, 1)); mRenderer()->iPrimitiveRenderer()->Render(); } }; // namespace
BOOL CLanguage::TranslateMenu( CMenu* pMenu, const int nMenuID, BOOL bTopLevel ) { CMenu* pChildMenu = NULL; static CUString strMissing; BOOL bReturn = TRUE; static int nPopUpIdx = 0; if ( bTopLevel ) { nPopUpIdx = MAKELPARAM( 0, nMenuID ); strMissing = _T( "" ); } DWORD i = pMenu->GetMenuItemCount(); for( i = 0; i < pMenu->GetMenuItemCount(); i++ ) { pChildMenu = pMenu->GetSubMenu( i ); int nItemID = pMenu->GetMenuItemID( i ); if ( MENU_SEPARARTOR != nItemID ) { CUString strLang; if ( bTopLevel ) { strLang = GetMainMenuItem( nMenuID, i ); } else { if ( MENU_POPUP != nItemID ) { strLang = GetSubMenuItem( nItemID ); } else { strLang = GetSubMenuItem( nPopUpIdx ); nPopUpIdx++; } } if ( MENU_POPUP != nItemID ) { CUStringConvert strCnv; if ( !strLang.IsEmpty() ) { pMenu->ModifyMenu( nItemID, MF_STRING, nItemID, strCnv.ToT( strLang ) ); } else { CString strTmp; pMenu->GetMenuString( nItemID, strTmp, MF_BYCOMMAND ); ReportMissingID( nItemID, CUString( strTmp ), 1 ); } } else { int nPosition = UINT( pChildMenu->m_hMenu ); if ( !strLang.IsEmpty() ) { int nPosition = UINT( pChildMenu->m_hMenu ); CUStringConvert strCnv; pMenu->ModifyMenu( UINT( pChildMenu->m_hMenu ), MF_STRING | MF_POPUP, UINT( pChildMenu->m_hMenu ), strCnv.ToT( strLang ) ); } else { if ( bTopLevel ) { CString strTmp; pMenu->GetMenuString( i, strTmp, MF_BYPOSITION ); strMissing += _W( "#" ) + CUString( strTmp ); } else { CString strTmp; pMenu->GetMenuString( 0, strTmp, MF_BYPOSITION ); ReportMissingID( nItemID, CUString( strTmp ), 1 ); } } TranslateMenu( pMenu->GetSubMenu(i), -1, FALSE ); } } } if ( bTopLevel ) { if ( !strMissing.IsEmpty() ) { ReportMissingID( nMenuID, strMissing + _W( "#" ), 1 ); } } return bReturn; }
CDEX_ERR CRipInfoDB::GetStatusInfo( int nTrack, DWORD& dwJitterErrors ) { BOOL bFinishedProperly = FALSE; BOOL bPresentInDB = FALSE; BOOL bAborted = FALSE; CDEX_ERR result = CDEX_OK; dwJitterErrors = 0; // Open file for append m_pFile = CDexOpenFile( m_strFileName, _W( "r" ) ); if ( NULL != m_pFile ) { // Loop through all entries while( !feof( m_pFile ) ) { TCHAR lpszLine[ 1024 ] = {'\0',}; int nCurrentTrack; // Clear string memset(lpszLine,0x00,sizeof(lpszLine)); // Read the next line from the file _fgetts( lpszLine, sizeof( lpszLine ), m_pFile ); // Get track number nCurrentTrack = _ttoi( &lpszLine[ 1 ] ); if ( nCurrentTrack == nTrack ) { bPresentInDB=TRUE; switch ( lpszLine[ 6 ] ) { case 'J': dwJitterErrors++ ; break; case 'A': bAborted = TRUE; break; case 'C': bFinishedProperly = TRUE; break; } } } fclose( m_pFile ); m_pFile = NULL; } if ( dwJitterErrors > 0 ) { result = CDEX_JITTER_ERROR; } else if ( bAborted ) { result = CDEX_ERROR; } else if ( bPresentInDB && bFinishedProperly ) { result = CDEX_RIPPING_DONE; } return result; }
UINT CAutoDetect::OnStartDetection(void *lpParam) { bThreadActive=TRUE; int nInsertItem=0; int Endian=0; CUString strTmp; CUString strOk; CUString strRead; CUString strEbl; CUString strEnd; CUString strDens; CUString strAtapi; g_pThread->BeginWaitCursor(); CAutoDetect* pDlg=(CAutoDetect*)lpParam; CDROMPARAMS cdTest; CR_GetCDROMParameters(&cdTest); CUString ReadMethodDescr[]={ _W("MMC "), _W("Standard"), _W("Nec "), _W("Sony "), _W("MMC1 "), _W("MMC2 "), _W("MMC3 "), _W("Read C1 "), _W("Read C2 "), _W("Read C3 "), _W("MMC4 "), _W("????????")}; CUString EnableDescr[]={ g_language.GetString( IDS_NONE ), g_language.GetString( IDS_STANDARD ), _W( "????" )}; // Write header to Log file dbgFile.printf( "ATAPI\tREAD\t\tENABLE\t\t%DENS\tENDIAN\tRESULT\n" ); for (int atapi = 0; atapi < NUMATAPI; atapi++ ) { if ( 0 == atapi ) { cdTest.DriveTable.bAtapi = FALSE; strAtapi = g_language.GetString( IDNO ); } else { cdTest.DriveTable.bAtapi = TRUE; strAtapi = g_language.GetString( IDYES ); } for (int rm = 0; rm < NUMREADMETHODS; rm++ ) { strRead=ReadMethodDescr[ rm ]; for (int en=0;en<NUMENABLEMODES;en++) { strEbl = EnableDescr[ en ]; for (int ds=0;ds<NUMDENSITIES;ds++) { cdTest.DriveTable.nDensity = CheckDensities[ds]; strDens.Format( _W( "%2x" ), cdTest.DriveTable.nDensity ); CUStringConvert strCnv; CUStringConvert strCnv1; CUStringConvert strCnv2; CUStringConvert strCnv3; // Log what we are doing to file dbgFile.printf("%s\t%s\t%s\t%s\t", strCnv.ToACP( strAtapi ), strCnv1.ToACP( strRead ), strCnv2.ToACP( strEbl ), strCnv3.ToACP( strDens ) ); cdTest.DriveTable.ReadMethod= READMETHOD( rm ); switch ( cdTest.DriveTable.ReadMethod ) { case READMMC: case READMMC2: case READMMC3: case READMMC4: cdTest.DriveTable.SetSpeed= SPEEDMMC; break; case READSONY: cdTest.DriveTable.SetSpeed= SPEEDSONY; break; case READ10: case READNEC: case READC1: case READC2: case READC3: default: cdTest.DriveTable.SetSpeed= SPEEDNONE; break; } cdTest.DriveTable.EnableMode= ENABLEMODE(en); cdTest.DriveTable.Endian = ENDIAN_LITTLE; CDEX_ERR err = TestDrive( cdTest ); strEnd = _T( "-" ); if (err==CDEX_OK) { strOk = g_language.GetString( IDS_PASS ); if ( ENDIAN_LITTLE == cdTest.DriveTable.Endian ) { strEnd = g_language.GetString( IDS_LITTLEENDIAN ); } else { strEnd = g_language.GetString( IDS_BIGENDIAN ); } } else { strOk = g_language.GetString( IDS_FAIL ); } pDlg->m_List.InsertItem( nInsertItem, strCnv.ToT( strRead ) ); pDlg->m_List.SetItemText( nInsertItem,1,strCnv.ToT( strAtapi ) ); pDlg->m_List.SetItemText( nInsertItem,2,strCnv.ToT( strEbl ) ); pDlg->m_List.SetItemText( nInsertItem,3,strCnv.ToT( strDens ) ); pDlg->m_List.SetItemText( nInsertItem,4,strCnv.ToT( strEnd ) ); pDlg->m_List.SetItemText( nInsertItem,5,strCnv.ToT( strOk ) ); myDriveTable[nCurrentDrive++]=cdTest.DriveTable; ASSERT(nCurrentDrive<=nNumTableEntries); // Log success dbgFile.printf("%s\t%s\n",strEnd,strOk); nInsertItem++; ::Sleep(0); if (pDlg->m_bAbort) { pDlg-> GetDlgItem(IDC_ABORT)->EnableWindow(FALSE); pDlg->GetDlgItem(IDOK)->EnableWindow(TRUE); g_pThread->EndWaitCursor(); return 0; } } } } } pDlg-> GetDlgItem(IDC_ABORT)->EnableWindow(FALSE); pDlg->GetDlgItem(IDOK)->EnableWindow(TRUE); g_pThread->EndWaitCursor(); return 0; }
void String::print(wostream& o) const { o << _W('"'); nV::print(str.c_str(), o); o << _W('"'); }
void cPVCamera::OnDraw() { if(mpFont) mpFont->Draw(cVector2f(5,5),12,cColor(1,1),eFontAlign_Left,_W("FPS: %.1f"),mpGame->GetFPS()); }
void Real::print(wostream& o) const { long exp; const size_t n_digits = static_cast<size_t>(LOG_10_2 * prec + 0.5); const size_t req_size = n_digits + 2; char* buf = new char[req_size]; const char* const buf2 = mpf_get_str(buf, &exp, 10, n_digits, mpf); wstring t(buf2, buf2 + strlen(buf2)); delete buf; wcs s = t.c_str(); if (exp > 0) { if (s[0] == _W('-')) { if (exp + 1 <= static_cast<long>(t.size())) { o.write(s, exp + 1); o << _W('.') << s + exp + 1; } else { o << s; o << wstring(exp + 1 - t.size(), _W('0')); o << _W('.'); } } else { if (exp <= static_cast<long>(t.size())) { o.write(s, exp); o << _W('.') << s + exp; } else { o << s; o << wstring(exp - t.size(), _W('0')); o << _W('.'); } } } else { if (s[0] == _W('-')) o << _W("-0.") << wstring(-exp, _W('0')) << s + 1; else o << _W("0.") << wstring(-exp, _W('0')) << s; } }
CUString COpenFileDlg::GetFilePath() { return m_strDir + _W( "\\" ) + m_strFileName; }
String IOMLCode::encodeToCss(shared_ptr<OMLContext> context, shared_ptr<OMLItem> i, const String& text) { OS_ASSERT(context != nullptr); if(text.empty()) return String::EMPTY; std::wstring out = text.to_wide(); // Qui cerco le parentesi '(' e ')'. // Se le trovo e sono di un "url(..)" trasformo l'url, altrimenti // le tolgo. // Basato su IPB 2.1, che rimuove radicalmente le parentesi nei parametri, evitando chiamate a expression(), url() etc.. // In realtà per ora qui rimuovo solo '(', non ')'. E' da sistemare. std::wstring::size_type posCurrent = 0; for(;;) { std::wstring::size_type posS = out.find(_W("("), posCurrent); if(posS == String::npos) break; bool transform = true; if(posS>3) { std::wstring prefix = out.substr(posS-3,4); algorithms::to_lower(prefix); if(prefix == _W("url(")) { String::size_type posE = out.find(_W(")"), posS); if(posE != String::npos) { std::wstring url = out.substr(posS+1,posE-posS-1); url = encodeResourceUrl(context, i, url).to_wide(); out = out.substr(0,posS+1) + url + out.substr(posE); posCurrent = posS + url.length() + 1; transform = false; } } else if(prefix == _W("rgb(")) { // VERYURGENT, da testare con // [div style="color:rgb(255, 255, 0);"]prova[/div] // La 0.12 lo toglieva transform = false; posCurrent = posS + 3; } } if(transform) { // Lo tolgo. out = out.substr(0,posS) + out.substr(posS+1); } } return out; /* 0.11 String::size_type posCurrent = 0; for(;;) { String::size_type posS = out.find(_S("url("), posCurrent); if(posS == String::npos) break; String::size_type posE = out.find(_S(")"), posS); if(posE == String::npos) break; String url = out.substr(posS+4,posE-posS-4); url = encodeImageUrl(context, i, url); out = out.substr(0,posS) + _S("url(") + url + _S(")") + out.substr(posE+1); posCurrent += url.length() + 1; } return out; */ }
void RunVisitorT<T>::visitprivate(const OpExp &e) { InternalType * pITL = NULL, * pITR = NULL, * pResult = NULL; try { /*getting what to assign*/ e.getLeft().accept(*this); if (isSingleResult() == false) { clearResult(); std::wostringstream os; os << _W("Incompatible output argument.\n"); //os << ((Location)e.right_get().getLocation()).getLocationString() << std::endl; throw ast::InternalError(os.str(), 999, e.getRight().getLocation()); } pITL = getResult(); /*getting what to assign*/ e.getRight().accept(*this); if (isSingleResult() == false) { clearResult(); std::wostringstream os; os << _W("Incompatible output argument.\n"); //os << ((Location)e.right_get().getLocation()).getLocationString() << std::endl; throw ast::InternalError(os.str(), 999, e.getRight().getLocation()); } pITR = getResult(); if (pITL->getType() == GenericType::ScilabImplicitList) { ImplicitList* pIL = pITL->getAs<ImplicitList>(); if (pIL->isComputable()) { pITL = pIL->extractFullMatrix(); pIL->killMe(); } } if (pITR->getType() == GenericType::ScilabImplicitList) { ImplicitList* pIR = pITR->getAs<ImplicitList>(); if (pIR->isComputable()) { pITR = pIR->extractFullMatrix(); pIR->killMe(); } } switch (e.getOper()) { case OpExp::plus : { pResult = GenericPlus(pITL, pITR); break; } case OpExp::unaryMinus : { pResult = GenericUnaryMinus(pITR); break; } case OpExp::minus : { pResult = GenericMinus(pITL, pITR); break; } case OpExp::times: { pResult = GenericTimes(pITL, pITR); break; } case OpExp::ldivide: { pResult = GenericLDivide(pITL, pITR); break; } case OpExp::dotldivide : { pResult = GenericDotLDivide(pITL, pITR); break; } case OpExp::rdivide: { pResult = GenericRDivide(pITL, pITR); break; } case OpExp::dotrdivide : { pResult = GenericDotRDivide(pITL, pITR); break; } case OpExp::dottimes : { pResult = GenericDotTimes(pITL, pITR); break; } case OpExp::dotpower : { pResult = GenericDotPower(pITL, pITR); break; } case OpExp::eq : { pResult = GenericComparisonEqual(pITL, pITR); break; } case OpExp::ne : { pResult = GenericComparisonNonEqual(pITL, pITR); break; } case OpExp::lt : { pResult = GenericLess(pITL, pITR); break; } case OpExp::le : { pResult = GenericLessEqual(pITL, pITR); break; } case OpExp::gt : { pResult = GenericGreater(pITL, pITR); break; } case OpExp::ge : { pResult = GenericGreaterEqual(pITL, pITR); break; } case OpExp::power : { pResult = GenericPower(pITL, pITR); break; } case OpExp::krontimes : { pResult = GenericKrontimes(pITL, pITR); break; } case OpExp::kronrdivide : { pResult = GenericKronrdivide(pITL, pITR); break; } case OpExp::kronldivide : { pResult = GenericKronldivide(pITL, pITR); break; } default : break; } //overloading if (pResult == NULL) { // We did not have any algorithm matching, so we try to call OverLoad pResult = callOverloadOpExp(e.getOper(), pITL, pITR); } setResult(pResult); //clear left and/or right operands if (pResult != pITL) { pITL->killMe(); } if (pResult != pITR) { pITR->killMe(); } } catch (ast::InternalError& error) { setResult(NULL); if (pResult) { pResult->killMe(); } if (pITL && (pITL != pResult)) { pITL->killMe(); } if (pITR && (pITR != pResult)) { pITR->killMe(); } error.SetErrorLocation(e.getLocation()); throw error; } /*if (e.getDecorator().res.isConstant()) { }*/ }
void BuildFileName( CUString strFormat, CUString strArray[NUMFILENAME_IDS], CUString& strName,CUString& strDir) { CUString strTmp( strFormat ); int nPos = 0; int i; for ( i=0; i<NUMFILENAME_IDS; i++ ) { strArray[i] = FixFileNameString( strArray[i] ); } // loop through all the tokens while ( (( nPos = strTmp.Find( _T( '%' ),nPos ) ) >=0 ) && ( nPos + 1 < strTmp.GetLength() ) ) { ENUM_FILENAME_CONVERTS convertType = FILENAME_CONVERT_NONE; int nPercentID = 0; int nSkipChars = 2; WCHAR chEval = strTmp.GetAt( nPos + 1 ); if ( _W( 'l' ) == chEval ) { convertType = FILENAME_CONVERT_LOWER; chEval = strTmp.GetAt( nPos + 2 ); nSkipChars++; } if ( _W( 'u' ) == chEval ) { convertType = FILENAME_CONVERT_UPPER; chEval = strTmp.GetAt( nPos + 2 ); nSkipChars++; } if ( _W( 'c' ) == chEval ) { convertType = FILENAME_CONVERT_FCEW_UPPER; chEval = strTmp.GetAt( nPos + 2 ); nSkipChars++; } if ( _W( 'f' ) == chEval ) { convertType = FILENAME_CONVERT_FC_UPPER; chEval = strTmp.GetAt( nPos + 2 ); nSkipChars++; } // Get %ID number switch ( chEval ) { case '1': nPercentID = 0; break; case '2': nPercentID = 1; break; case '3': nPercentID = 2; break; case '4': nPercentID = 3; break; case '5': nPercentID = 4; break; case '6': nPercentID = 5; break; case '7': nPercentID = 6; break; case '8': nPercentID = 7; break; case 'Y': nPercentID = 8; break; case 'G': nPercentID = 9; break; case 'A': nPercentID = 10; break; default: nPercentID = -1; nPos++; break; } if ( nPercentID >= 0 && nPercentID < NUMFILENAME_IDS ) { CUString strLeft( strTmp.Left( nPos ) ); CUString strMid( strArray[ nPercentID ] ); CUString strRight( strTmp.Right( strTmp.GetLength() - nPos - nSkipChars ) ); // do filename mangling strMid = FormatTrackNameString( strMid, convertType ); strTmp = strLeft + strMid + strRight; } else { // Delete token // strTmp = strTmp.Left( nPos ) + strTmp.Right( strTmp.GetLength() - nPos - 1 ); } } // Split result in a directory and file name portion // Search for last backslash nPos = strTmp.ReverseFind( _T( '\\' ) ); if ( nPos >= 2 ) { // OK, we've found the backsplash, do the split strDir = strTmp.Left( nPos + 1 ); strName = strTmp.Right( strTmp.GetLength() - nPos - 1 ); } else { // Only a filename, just assign the string to the filename and clear the directory strDir = _T( "" ); strName = strTmp; } strDir.TrimLeft(); strDir.TrimRight(); // remove spaces before the directory separator and double backslashes INT nIndex = 0; while ( nIndex < strDir.GetLength() ) { if ( _T( '\\' ) == strDir[ nIndex ] ) { if ( nIndex > 0 ) { if ( ( _T( '\\' ) == strDir[ nIndex - 1 ] ) || ( _T( ' ' ) == strDir[ nIndex - 1 ] )) { strDir = strDir.Left( nIndex ) + strDir.Mid( nIndex + 1 ); nIndex = 0; continue; } } } if ( _T( ' ' ) == strDir[ nIndex ] ) { if ( nIndex > 0 ) { if ( ( _T( '\\' ) == strDir[ nIndex - 1 ] ) ) { strDir = strDir.Left( nIndex ) + strDir.Mid( nIndex + 1 ); nIndex = 0; continue; } } } nIndex++; } strDir.TrimLeft(); strDir.TrimRight(); strName.TrimLeft(); strName.TrimRight(); }